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
<file_sep># DEMETER2 in Stan [DEMETER2 website](https://depmap.org/R2-D2/) [data](https://figshare.com/articles/DEMETER2_data/6025238) [Paper](https://www.nature.com/articles/s41467-018-06916-5) [Supplemental](https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-018-06916-5/MediaObjects/41467_2018_6916_MOESM1_ESM.pdf) <file_sep># DEMETER2 in Stan ```python import pystan import numpy as np import pandas as pd from matplotlib import pyplot as plt import arviz as az from pathlib import Path import seaborn as sns from timeit import default_timer as timer import warnings import re from notebook_modules.pystan_helpers import StanModel_cache ``` ```python plt.style.use('seaborn-whitegrid') plt.rcParams['figure.figsize'] = (10.0, 7.0) plt.rcParams['axes.titlesize'] = 18 plt.rcParams['axes.labelsize'] = 15 modeling_data_dir = Path('../modeling_data') warnings.filterwarnings(action='ignore', message='Argument backend_kwargs has not effect in matplotlib.plot_distSupplied value won\'t be used') ``` ## Data preparation ```python modeling_data = pd.read_csv(modeling_data_dir / 'subset_modeling_data.csv') modeling_data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> <th>batch</th> <th>gene_symbol</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>ln215_central_nervous_system</td> <td>1.966515</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>1</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>ln382_central_nervous_system</td> <td>1.289606</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>2</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>efo21_ovary</td> <td>0.625725</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>3</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>jhesoad1_oesophagus</td> <td>1.392272</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>4</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>km12_large_intestine</td> <td>0.820838</td> <td>1</td> <td>EIF6</td> </tr> </tbody> </table> </div> ## Exploratory data analysis ```python genes = set(modeling_data.gene_symbol.to_list()) fig, axes = plt.subplots(5, 3, figsize=(9, 9)) for ax, gene in zip(axes.flat, genes): lfc = modeling_data[modeling_data.gene_symbol == gene].lfc sns.distplot(lfc, kde=True, hist=False, rug=True, ax=ax, kde_kws={'shade': True}, color='b') y_data = ax.lines[0].get_ydata() ax.vlines(x=0, ymin=0, ymax=np.max(y_data) * 1.05, linestyles='dashed') ax.set_title(gene, fontsize=12) ax.set_xlabel(None) axes[4, 2].axis('off') axes[4, 1].axis('off') fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_6_0.png) ```python cell_lines = set(modeling_data.cell_line.to_list()) for cell_line in cell_lines: lfc = modeling_data[modeling_data.cell_line == cell_line].lfc sns.distplot(lfc, kde=True, hist=False, label=None, kde_kws={'alpha': 0.2}) plt.title('LFC distributions') plt.xlabel('LFC') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_7_0.png) ```python sns.distplot(modeling_data.lfc) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_8_0.png) ```python modeling_data[['barcode_sequence', 'gene_symbol']].drop_duplicates().groupby('gene_symbol').count() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> </tr> <tr> <th>gene_symbol</th> <th></th> </tr> </thead> <tbody> <tr> <th>BRAF</th> <td>8</td> </tr> <tr> <th>COG3</th> <td>5</td> </tr> <tr> <th>COL8A1</th> <td>5</td> </tr> <tr> <th>EGFR</th> <td>19</td> </tr> <tr> <th>EIF6</th> <td>5</td> </tr> <tr> <th>ESPL1</th> <td>5</td> </tr> <tr> <th>GRK5</th> <td>5</td> </tr> <tr> <th>KRAS</th> <td>11</td> </tr> <tr> <th>PTK2</th> <td>23</td> </tr> <tr> <th>RC3H2</th> <td>4</td> </tr> <tr> <th>RHBDL2</th> <td>5</td> </tr> <tr> <th>SDHB</th> <td>5</td> </tr> <tr> <th>TRIM39</th> <td>9</td> </tr> </tbody> </table> </div> ```python lfc_corr = modeling_data \ .pivot(index='cell_line', columns='barcode_sequence', values='lfc') \ .corr() mask = np.triu(np.ones_like(lfc_corr, dtype=np.bool), k=0) f, ax = plt.subplots(figsize=(15, 13)) cmap = sns.diverging_palette(220, 10, as_cmap=True) sns.heatmap(lfc_corr, mask=mask, cmap=cmap, center=0, square=True, linewidths=0.5, cbar_kws={'shrink': 0.5}) plt.xlabel('barcode') plt.ylabel('barcode') plt.title('Correlation of LFC of barcodes') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_10_0.png) ## Modeling ```python models_dir = Path('..', 'models') ``` ```python modeling_data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> <th>batch</th> <th>gene_symbol</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>ln215_central_nervous_system</td> <td>1.966515</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>1</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>ln382_central_nervous_system</td> <td>1.289606</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>2</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>efo21_ovary</td> <td>0.625725</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>3</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>jhesoad1_oesophagus</td> <td>1.392272</td> <td>1</td> <td>EIF6</td> </tr> <tr> <th>4</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>km12_large_intestine</td> <td>0.820838</td> <td>1</td> <td>EIF6</td> </tr> </tbody> </table> </div> Select only a few cell lines while model building. ```python len(np.unique(modeling_data.cell_line)) ``` 501 ```python np.random.seed(123) cell_lines = np.random.choice(np.unique(modeling_data.cell_line), 40) modeling_data = modeling_data[modeling_data.cell_line.isin(cell_lines)] modeling_data.shape ``` (3334, 5) ```python np.unique(modeling_data.gene_symbol) ``` array(['BRAF', 'COG3', 'COL8A1', 'EGFR', 'EIF6', 'ESPL1', 'GRK5', 'KRAS', 'PTK2', 'RC3H2', 'RHBDL2', 'SDHB', 'TRIM39'], dtype=object) ```python # model_testing_genes = ['COG3', 'KRAS', 'COL8A1', 'EIF6'] # modeling_data = modeling_data[modeling_data.gene_symbol.isin(model_testing_genes)] ``` ```python genes = set(modeling_data.gene_symbol.to_list()) fig, axes = plt.subplots(1, 4, figsize=(10, 3)) for ax, gene in zip(axes.flat, genes): lfc = modeling_data[modeling_data.gene_symbol == gene].lfc sns.distplot(lfc, kde=True, hist=True, ax=ax, color='b') y_data = ax.lines[0].get_ydata() ax.vlines(x=0, ymin=0, ymax=np.max(y_data) * 1.05, linestyles='dashed') ax.set_title(gene, fontsize=12) ax.set_xlabel(None) fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_19_0.png) ```python def add_categorical_idx(df, col): df[f'{col}_idx'] = df[col].astype('category').cat.codes + 1 return df for col in ['barcode_sequence', 'cell_line', 'gene_symbol']: modeling_data = add_categorical_idx(modeling_data, col) modeling_data = modeling_data.reset_index(drop=True) modeling_data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> <th>batch</th> <th>gene_symbol</th> <th>barcode_sequence_idx</th> <th>cell_line_idx</th> <th>gene_symbol_idx</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>efo21_ovary</td> <td>0.625725</td> <td>1</td> <td>EIF6</td> <td>1</td> <td>11</td> <td>5</td> </tr> <tr> <th>1</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>dbtrg05mg_central_nervous_system</td> <td>2.145082</td> <td>2</td> <td>EIF6</td> <td>1</td> <td>9</td> <td>5</td> </tr> <tr> <th>2</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>bt20_breast</td> <td>0.932751</td> <td>2</td> <td>EIF6</td> <td>1</td> <td>3</td> <td>5</td> </tr> <tr> <th>3</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>sw1783_central_nervous_system</td> <td>1.372030</td> <td>2</td> <td>EIF6</td> <td>1</td> <td>36</td> <td>5</td> </tr> <tr> <th>4</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>kns60_central_nervous_system</td> <td>0.803835</td> <td>2</td> <td>EIF6</td> <td>1</td> <td>18</td> <td>5</td> </tr> </tbody> </table> </div> Binary matrix of $[shRNA \times gene]$. ```python shrna_gene_matrix = modeling_data[['barcode_sequence_idx', 'gene_symbol_idx']] \ .drop_duplicates() \ .reset_index(drop=True) \ .assign(value = lambda df: np.ones(df.shape[0], dtype=int)) \ .pivot(index='barcode_sequence_idx', columns='gene_symbol_idx', values='value') \ .fillna(0) \ .to_numpy() \ .astype(int) shrna_gene_matrix ``` array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 1]]) ```python shrna_gene_matrix.shape ``` (109, 13) ## Model 1. Just an intercept $$ D \sim N(\mu, \sigma) \\ \mu = \alpha \\ \alpha \sim N(0, 5) \\ \sigma \sim \text{HalfCauchy}(0, 5) $$ **Model data.** ```python d2_m1_data = { 'N': int(modeling_data.shape[0]), 'y': modeling_data.lfc } ``` **Compile model.** ```python d2_m1_file = models_dir / 'd2_m1.cpp' d2_m1 = StanModel_cache(file=d2_m1_file.as_posix()) ``` Using cached StanModel. ```python d2_m1_fit = d2_m1.sampling(data=d2_m1_data, iter=2000, chains=2) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) ```python pystan.check_hmc_diagnostics(d2_m1_fit) ``` {'n_eff': True, 'Rhat': True, 'divergence': True, 'treedepth': True, 'energy': True} ```python az_d2_m1 = az.from_pystan(posterior=d2_m1_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m1) az.summary(az_d2_m1) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> </tr> </thead> <tbody> <tr> <th>alpha</th> <td>-1.290</td> <td>0.030</td> <td>-1.347</td> <td>-1.235</td> <td>0.001</td> <td>0.0</td> <td>1958.0</td> <td>1952.0</td> <td>1925.0</td> <td>1230.0</td> <td>1.0</td> </tr> <tr> <th>sigma</th> <td>1.736</td> <td>0.021</td> <td>1.696</td> <td>1.775</td> <td>0.000</td> <td>0.0</td> <td>2269.0</td> <td>2269.0</td> <td>2273.0</td> <td>1545.0</td> <td>1.0</td> </tr> </tbody> </table> </div> ```python az.plot_trace(az_d2_m1) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_32_0.png) ```python az.plot_forest(az_d2_m1, combined=True) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_33_0.png) ```python az.plot_ppc(az_d2_m1, data_pairs={'y':'y_pred'}, num_pp_samples=50) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_34_0.png) ## Model 2. Varying intercept by shRNA $$ D_{i|s} \sim N(\mu_{i|s}, \sigma) \\ \mu = \alpha_{i|s} \\ \alpha \sim N(\mu_{\alpha}, \sigma_{\alpha}) \\ \mu_{\alpha} \sim N(0, 2) \\ \sigma_{\alpha} \sim \text{HalfCauchy}(0, 2) \\ \sigma \sim \text{HalfCauchy}(0, 5) $$ ### Generative model for a prior predictive check ```python N = 1000 S = 100 shrna_barcodes = list(range(1, S+1)) shrna_barcodes_idx = np.repeat(shrna_barcodes, N/S) ``` ```python d2_m2_gen_data = { 'N': N, 'S': S, 'shrna': shrna_barcodes_idx } ``` ```python d2_m2_gen_file = models_dir / 'd2_m2_generative.cpp' d2_m2_gen = StanModel_cache(file=d2_m2_gen_file.as_posix()) ``` Using cached StanModel. ```python d2_m2_gen_fit = d2_m2_gen.sampling(data=d2_m2_gen_data, iter=10, warmup=0, chains=1, algorithm='Fixed_param') ``` ```python az_d2_m2_gen = az.from_pystan(d2_m2_gen_fit) ``` ```python df = d2_m2_gen_fit.to_dataframe() \ .drop(['chain', 'draw', 'warmup'], axis=1) \ .melt(var_name='parameter', value_name='value') df = df[df.parameter.str.contains('alpha\[')] sns.distplot(df.value) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_42_0.png) ```python df = d2_m2_gen_fit.to_dataframe() \ .drop(['chain', 'draw', 'warmup'], axis=1) \ .melt(var_name='parameter', value_name='value') df = df[df.parameter.str.contains('y_pred')] sns.distplot(df.value) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_43_0.png) ```python sns.distplot(modeling_data.lfc) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_44_0.png) **Model data** ```python d2_m2_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'shrna': modeling_data.barcode_sequence_idx, 'y': modeling_data.lfc, } ``` ```python d2_m2_data['S'] ``` 109 **Compile model.** ```python d2_m2_file = models_dir / 'd2_m2.cpp' d2_m2 = StanModel_cache(file=d2_m2_file.as_posix()) ``` Using cached StanModel. ```python d2_m2_fit = d2_m2.sampling(data=d2_m2_data, iter=1000, chains=2) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) ```python pystan.check_hmc_diagnostics(d2_m2_fit) ``` {'n_eff': True, 'Rhat': True, 'divergence': True, 'treedepth': True, 'energy': True} ```python az_d2_m2 = az.from_pystan(posterior=d2_m2_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m2) az.summary(az_d2_m2).head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> </tr> </thead> <tbody> <tr> <th>mu_alpha</th> <td>-1.222</td> <td>0.124</td> <td>-1.481</td> <td>-1.001</td> <td>0.004</td> <td>0.003</td> <td>1058.0</td> <td>1058.0</td> <td>1082.0</td> <td>574.0</td> <td>1.01</td> </tr> <tr> <th>sigma_alpha</th> <td>1.276</td> <td>0.087</td> <td>1.132</td> <td>1.461</td> <td>0.003</td> <td>0.002</td> <td>1031.0</td> <td>1007.0</td> <td>1049.0</td> <td>643.0</td> <td>1.00</td> </tr> <tr> <th>alpha[0]</th> <td>0.714</td> <td>0.201</td> <td>0.330</td> <td>1.062</td> <td>0.006</td> <td>0.004</td> <td>1205.0</td> <td>1205.0</td> <td>1252.0</td> <td>551.0</td> <td>1.01</td> </tr> <tr> <th>alpha[1]</th> <td>-0.250</td> <td>0.190</td> <td>-0.616</td> <td>0.087</td> <td>0.007</td> <td>0.005</td> <td>836.0</td> <td>836.0</td> <td>847.0</td> <td>582.0</td> <td>1.00</td> </tr> <tr> <th>alpha[2]</th> <td>-0.784</td> <td>0.211</td> <td>-1.180</td> <td>-0.395</td> <td>0.006</td> <td>0.005</td> <td>1100.0</td> <td>1047.0</td> <td>1084.0</td> <td>668.0</td> <td>1.00</td> </tr> </tbody> </table> </div> ```python az.plot_trace(az_d2_m2, var_names=['mu_alpha', 'sigma_alpha', 'sigma']) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_53_0.png) ```python az.plot_forest(az_d2_m2, kind='ridgeplot', combined=True, var_names=['mu_alpha', 'sigma_alpha', 'sigma']) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_54_0.png) ```python az.plot_ppc(az_d2_m2, data_pairs={'y':'y_pred'}, num_pp_samples=50) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_55_0.png) ```python d2_m2_fit.to_dataframe().head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>chain</th> <th>draw</th> <th>warmup</th> <th>mu_alpha</th> <th>sigma_alpha</th> <th>alpha[1]</th> <th>alpha[2]</th> <th>alpha[3]</th> <th>alpha[4]</th> <th>alpha[5]</th> <th>...</th> <th>y_pred[3332]</th> <th>y_pred[3333]</th> <th>y_pred[3334]</th> <th>lp__</th> <th>accept_stat__</th> <th>stepsize__</th> <th>treedepth__</th> <th>n_leapfrog__</th> <th>divergent__</th> <th>energy__</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0</td> <td>0</td> <td>0</td> <td>-1.263567</td> <td>1.286463</td> <td>0.691531</td> <td>-0.410589</td> <td>-0.486056</td> <td>0.140605</td> <td>-2.252227</td> <td>...</td> <td>-1.821982</td> <td>-4.610282</td> <td>-0.057629</td> <td>-2395.220205</td> <td>0.834995</td> <td>0.418915</td> <td>5</td> <td>55</td> <td>0</td> <td>2445.602866</td> </tr> <tr> <th>1</th> <td>0</td> <td>1</td> <td>0</td> <td>-1.294416</td> <td>1.323071</td> <td>0.697405</td> <td>-0.267598</td> <td>-1.044003</td> <td>0.264281</td> <td>-2.362734</td> <td>...</td> <td>0.730910</td> <td>-0.803228</td> <td>-1.128669</td> <td>-2394.569464</td> <td>0.937689</td> <td>0.418915</td> <td>7</td> <td>143</td> <td>0</td> <td>2451.366998</td> </tr> <tr> <th>2</th> <td>0</td> <td>2</td> <td>0</td> <td>-1.374924</td> <td>1.356104</td> <td>0.803428</td> <td>-0.176478</td> <td>-1.007182</td> <td>0.161903</td> <td>-2.297076</td> <td>...</td> <td>-3.385013</td> <td>-1.969810</td> <td>0.468591</td> <td>-2395.033725</td> <td>0.853836</td> <td>0.418915</td> <td>3</td> <td>15</td> <td>0</td> <td>2456.917527</td> </tr> <tr> <th>3</th> <td>0</td> <td>3</td> <td>0</td> <td>-1.464064</td> <td>1.165498</td> <td>0.857390</td> <td>-0.004899</td> <td>-1.059237</td> <td>-0.043809</td> <td>-2.267916</td> <td>...</td> <td>0.264705</td> <td>0.080555</td> <td>0.108367</td> <td>-2395.912197</td> <td>0.954930</td> <td>0.418915</td> <td>5</td> <td>55</td> <td>0</td> <td>2449.214887</td> </tr> <tr> <th>4</th> <td>0</td> <td>4</td> <td>0</td> <td>-1.029178</td> <td>1.369234</td> <td>0.585008</td> <td>-0.558714</td> <td>-0.510735</td> <td>0.471418</td> <td>-2.217178</td> <td>...</td> <td>-2.383169</td> <td>-2.772807</td> <td>-0.843937</td> <td>-2396.046197</td> <td>0.936803</td> <td>0.418915</td> <td>3</td> <td>7</td> <td>0</td> <td>2450.746997</td> </tr> </tbody> </table> <p>5 rows × 3456 columns</p> </div> ## Model 3. Another varying intercept for target gene $$ D_{i|s} \sim N(\mu_{i|s}, \sigma) \\ \mu = \alpha_{i|s} + g_{i|l}\\ \alpha_s \sim N(\mu_{\alpha}, \sigma_{\alpha}) \\ g_l \sim N(\mu_g, \sigma_g) \\ \mu_{\alpha} \sim N(0, 2) \quad \sigma_{\alpha} \sim \text{HalfCauchy}(0, 10) \\ \mu_{g} \sim N(0, 2) \quad \sigma_{g} \sim \text{HalfCauchy}(0, 10) \\ \sigma \sim \text{HalfCauchy}(0, 10) $$ ```python d2_m3_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'L': np.max(modeling_data.gene_symbol_idx), 'shrna': modeling_data.barcode_sequence_idx, 'gene': modeling_data.gene_symbol_idx, 'y': modeling_data.lfc, } ``` **Compile model.** ```python d2_m3_file = models_dir / 'd2_m3.cpp' d2_m3 = StanModel_cache(file=d2_m3_file.as_posix()) ``` Using cached StanModel. ```python d2_m3_control = {'adapt_delta': 0.99, 'max_treedepth': 10} d2_m3_fit = d2_m3.sampling(data=d2_m3_data, iter=3000, warmup=1000, chains=4, control=d2_m3_control) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) WARNING:pystan:156 of 8000 iterations ended with a divergence (1.95 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:6 of 8000 iterations saturated the maximum tree depth of 10 (0.075 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation ```python pystan.check_hmc_diagnostics(d2_m3_fit) ``` WARNING:pystan:Rhat above 1.1 or below 0.9 indicates that the chains very likely have not mixed WARNING:pystan:156 of 8000 iterations ended with a divergence (1.95 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:6 of 8000 iterations saturated the maximum tree depth of 10 (0.075 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation {'n_eff': True, 'Rhat': False, 'divergence': False, 'treedepth': False, 'energy': True} ```python az_d2_m3 = az.from_pystan(posterior=d2_m3_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m3) az.summary(az_d2_m3).head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> </tr> </thead> <tbody> <tr> <th>mu_alpha</th> <td>-0.773</td> <td>1.167</td> <td>-2.439</td> <td>1.427</td> <td>0.270</td> <td>0.194</td> <td>19.0</td> <td>19.0</td> <td>21.0</td> <td>33.0</td> <td>1.14</td> </tr> <tr> <th>sigma_alpha</th> <td>1.242</td> <td>0.094</td> <td>1.087</td> <td>1.430</td> <td>0.005</td> <td>0.004</td> <td>356.0</td> <td>342.0</td> <td>406.0</td> <td>281.0</td> <td>1.01</td> </tr> <tr> <th>mu_g</th> <td>-0.514</td> <td>1.164</td> <td>-2.764</td> <td>1.165</td> <td>0.268</td> <td>0.193</td> <td>19.0</td> <td>19.0</td> <td>21.0</td> <td>36.0</td> <td>1.14</td> </tr> <tr> <th>sigma_g</th> <td>0.404</td> <td>0.219</td> <td>0.023</td> <td>0.757</td> <td>0.017</td> <td>0.012</td> <td>166.0</td> <td>166.0</td> <td>123.0</td> <td>71.0</td> <td>1.03</td> </tr> <tr> <th>alpha[0]</th> <td>1.455</td> <td>1.224</td> <td>-0.608</td> <td>3.800</td> <td>0.277</td> <td>0.199</td> <td>19.0</td> <td>19.0</td> <td>21.0</td> <td>37.0</td> <td>1.14</td> </tr> </tbody> </table> </div> ```python az.plot_trace(az_d2_m3, var_names=['g']) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_64_0.png) ```python az.plot_ppc(az_d2_m3, data_pairs={'y':'y_pred'}, num_pp_samples=50) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_65_0.png) ```python fit3_summary = az.summary(az_d2_m3) ``` ```python fit3_alpha_summary = fit3_summary[fit3_summary.index.str.contains('alpha\[')] shrna_idx = [re.search(r"\[([A-Za-z0-9_]+)\]", a).group(1) for a in fit3_alpha_summary.index] shrna_idx = [int(a) + 1 for a in shrna_idx] fit3_alpha_summary = fit3_alpha_summary \ .assign(barcode_sequence_idx = shrna_idx) \ .set_index('barcode_sequence_idx') \ .join(modeling_data[['barcode_sequence_idx', 'gene_symbol']] \ .drop_duplicates() \ .set_index('barcode_sequence_idx')) fit3_alpha_summary.head(10) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> <th>gene_symbol</th> </tr> <tr> <th>barcode_sequence_idx</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>1</th> <td>1.455</td> <td>1.224</td> <td>-0.608</td> <td>3.800</td> <td>0.277</td> <td>0.199</td> <td>19.0</td> <td>19.0</td> <td>21.0</td> <td>37.0</td> <td>1.14</td> <td>EIF6</td> </tr> <tr> <th>2</th> <td>0.073</td> <td>1.229</td> <td>-1.856</td> <td>2.445</td> <td>0.271</td> <td>0.195</td> <td>21.0</td> <td>21.0</td> <td>23.0</td> <td>33.0</td> <td>1.13</td> <td>GRK5</td> </tr> <tr> <th>3</th> <td>-0.060</td> <td>1.207</td> <td>-2.076</td> <td>2.311</td> <td>0.268</td> <td>0.192</td> <td>20.0</td> <td>20.0</td> <td>21.0</td> <td>38.0</td> <td>1.13</td> <td>EIF6</td> </tr> <tr> <th>4</th> <td>0.496</td> <td>1.229</td> <td>-1.501</td> <td>2.871</td> <td>0.277</td> <td>0.199</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>34.0</td> <td>1.13</td> <td>EGFR</td> </tr> <tr> <th>5</th> <td>-1.351</td> <td>1.202</td> <td>-3.423</td> <td>0.987</td> <td>0.267</td> <td>0.191</td> <td>20.0</td> <td>20.0</td> <td>21.0</td> <td>38.0</td> <td>1.13</td> <td>COL8A1</td> </tr> <tr> <th>6</th> <td>-0.715</td> <td>1.176</td> <td>-2.763</td> <td>1.527</td> <td>0.263</td> <td>0.189</td> <td>20.0</td> <td>20.0</td> <td>20.0</td> <td>36.0</td> <td>1.14</td> <td>KRAS</td> </tr> <tr> <th>7</th> <td>-0.446</td> <td>1.223</td> <td>-2.388</td> <td>1.881</td> <td>0.276</td> <td>0.198</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>34.0</td> <td>1.14</td> <td>PTK2</td> </tr> <tr> <th>8</th> <td>1.247</td> <td>1.198</td> <td>-0.769</td> <td>3.530</td> <td>0.267</td> <td>0.191</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>36.0</td> <td>1.13</td> <td>PTK2</td> </tr> <tr> <th>9</th> <td>0.447</td> <td>1.213</td> <td>-1.502</td> <td>2.785</td> <td>0.274</td> <td>0.196</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>36.0</td> <td>1.13</td> <td>PTK2</td> </tr> <tr> <th>10</th> <td>-0.718</td> <td>1.213</td> <td>-2.667</td> <td>1.644</td> <td>0.271</td> <td>0.195</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>34.0</td> <td>1.13</td> <td>BRAF</td> </tr> </tbody> </table> </div> ```python fit3_gene_summary = fit3_summary[fit3_summary.index.str.contains('g\[')] gene_idx = [re.search(r"\[([A-Za-z0-9_]+)\]", a).group(1) for a in fit3_gene_summary.index] gene_idx = [int(a) + 1 for a in gene_idx] fit3_gene_summary = fit3_gene_summary \ .assign(gene_symbol_idx = gene_idx) \ .set_index('gene_symbol_idx') \ .join(modeling_data[['gene_symbol_idx', 'gene_symbol']] \ .drop_duplicates() \ .set_index('gene_symbol_idx')) \ .reset_index(drop=False) fit3_gene_summary.head(10) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>gene_symbol_idx</th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> <th>gene_symbol</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>1</td> <td>-0.391</td> <td>1.199</td> <td>-2.725</td> <td>1.468</td> <td>0.272</td> <td>0.196</td> <td>19.0</td> <td>19.0</td> <td>22.0</td> <td>35.0</td> <td>1.13</td> <td>BRAF</td> </tr> <tr> <th>1</th> <td>2</td> <td>-0.386</td> <td>1.227</td> <td>-2.671</td> <td>1.768</td> <td>0.276</td> <td>0.198</td> <td>20.0</td> <td>20.0</td> <td>22.0</td> <td>34.0</td> <td>1.14</td> <td>COG3</td> </tr> <tr> <th>2</th> <td>3</td> <td>-0.906</td> <td>1.190</td> <td>-3.291</td> <td>1.072</td> <td>0.265</td> <td>0.190</td> <td>20.0</td> <td>20.0</td> <td>21.0</td> <td>36.0</td> <td>1.14</td> <td>COL8A1</td> </tr> <tr> <th>3</th> <td>4</td> <td>-0.241</td> <td>1.204</td> <td>-2.499</td> <td>1.583</td> <td>0.278</td> <td>0.199</td> <td>19.0</td> <td>19.0</td> <td>21.0</td> <td>32.0</td> <td>1.14</td> <td>EGFR</td> </tr> <tr> <th>4</th> <td>5</td> <td>-0.733</td> <td>1.196</td> <td>-3.147</td> <td>1.178</td> <td>0.268</td> <td>0.193</td> <td>20.0</td> <td>20.0</td> <td>21.0</td> <td>37.0</td> <td>1.14</td> <td>EIF6</td> </tr> <tr> <th>5</th> <td>6</td> <td>-0.792</td> <td>1.197</td> <td>-3.210</td> <td>1.147</td> <td>0.260</td> <td>0.187</td> <td>21.0</td> <td>21.0</td> <td>22.0</td> <td>40.0</td> <td>1.13</td> <td>ESPL1</td> </tr> <tr> <th>6</th> <td>7</td> <td>-0.333</td> <td>1.221</td> <td>-2.678</td> <td>1.531</td> <td>0.273</td> <td>0.196</td> <td>20.0</td> <td>20.0</td> <td>23.0</td> <td>35.0</td> <td>1.13</td> <td>GRK5</td> </tr> <tr> <th>7</th> <td>8</td> <td>-0.798</td> <td>1.166</td> <td>-3.100</td> <td>1.077</td> <td>0.266</td> <td>0.191</td> <td>19.0</td> <td>19.0</td> <td>20.0</td> <td>34.0</td> <td>1.15</td> <td>KRAS</td> </tr> <tr> <th>8</th> <td>9</td> <td>-0.222</td> <td>1.187</td> <td>-2.405</td> <td>1.640</td> <td>0.272</td> <td>0.195</td> <td>19.0</td> <td>19.0</td> <td>22.0</td> <td>35.0</td> <td>1.13</td> <td>PTK2</td> </tr> <tr> <th>9</th> <td>10</td> <td>-0.560</td> <td>1.220</td> <td>-2.939</td> <td>1.463</td> <td>0.257</td> <td>0.184</td> <td>23.0</td> <td>23.0</td> <td>24.0</td> <td>40.0</td> <td>1.12</td> <td>RC3H2</td> </tr> </tbody> </table> </div> ```python for i in range(fit3_gene_summary.shape[0]): plt.plot(np.repeat(fit3_gene_summary.loc[i, 'gene_symbol'], 2), [fit3_gene_summary.loc[i, 'hdi_3%'], fit3_gene_summary.loc[i, 'hdi_97%']], color='red', alpha=0.5) plt.scatter(fit3_gene_summary['gene_symbol'], fit3_gene_summary['mean'], s=100, c='r', label='gene') plt.scatter(fit3_alpha_summary['gene_symbol'], fit3_alpha_summary['mean'], alpha=0.3, s=75, c='b', label='shRNA') plt.title('shRNA and gene mean values') plt.xlabel('target gene') plt.ylabel('estimated effect on LFC') plt.legend() plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_69_0.png) ## Model 4. Parameters for difference between average gene effect and cell line-specific effect Note that the varying intercept for shRNA has been renamed from $\alpha$ to $c$. $\bar g_{l}$ is the average effect of knocking-down gene $l$ while $g_{jl}$ is the cell line $j$-specific effect of knocking-down $l$. There is now also varying population level standard deviations for each shRNA $\sigma_s$. This seems to help reduce divergences during sampling by modeling differences in standard deviation for each shRNA. $$ D_{i|s} \sim N(\mu_{i|s}, \sigma_s) \\ \mu = c_{i|s} + \bar g_{i|l} + g_{i|jl} \\ c_s \sim N(0, \sigma_c) \\ \bar g_l \sim N(\mu_{\bar g}, \sigma_{\bar g}) \\ g_{jl} \sim N(0, \sigma_g) \\ \sigma_c \sim \text{HalfNormal}(0, 3) \\ \mu_{\bar g} \sim N(0, 2) \quad \sigma_{\bar g} \sim \text{HalfNormal}(0, 10) \\ \sigma_g \sim \text{HalfNormal}(0, 5) \\ \sigma_s \sim \text{HalfNormal}(\mu_\sigma, \sigma_\sigma) \\ \mu_\sigma \sim \text{HalfNormal}(0, 2) \quad \sigma_\sigma \sim \text{HalfNormal}(0, 1) \\ $$ ```python d2_m4_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'L': np.max(modeling_data.gene_symbol_idx), 'J': np.max(modeling_data.cell_line_idx), 'shrna': modeling_data.barcode_sequence_idx, 'gene': modeling_data.gene_symbol_idx, 'cell_line': modeling_data.cell_line_idx, 'y': modeling_data.lfc, } ``` **Compile model.** ```python d2_m4_file = models_dir / 'd2_m4.cpp' d2_m4 = StanModel_cache(file=d2_m4_file.as_posix()) ``` Using cached StanModel. ```python d2_m4_control = {'adapt_delta': 0.99, 'max_treedepth': 10} d2_m4_fit = d2_m4.sampling(data=d2_m4_data, iter=3000, warmup=1000, chains=4, control=d2_m4_control) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) WARNING:pystan:64 of 8000 iterations ended with a divergence (0.8 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. ```python pystan.check_hmc_diagnostics(d2_m4_fit) ``` WARNING:pystan:64 of 8000 iterations ended with a divergence (0.8 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. {'n_eff': True, 'Rhat': True, 'divergence': False, 'treedepth': True, 'energy': True} ```python az_d2_m4 = az.from_pystan(posterior=d2_m4_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m4) az.summary(az_d2_m4).head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> </tr> </thead> <tbody> <tr> <th>sigma_c</th> <td>1.237</td> <td>0.092</td> <td>1.068</td> <td>1.410</td> <td>0.001</td> <td>0.001</td> <td>5649.0</td> <td>5594.0</td> <td>5720.0</td> <td>5594.0</td> <td>1.00</td> </tr> <tr> <th>mu_gbar</th> <td>-1.271</td> <td>0.181</td> <td>-1.627</td> <td>-0.944</td> <td>0.005</td> <td>0.003</td> <td>1339.0</td> <td>1339.0</td> <td>1324.0</td> <td>3014.0</td> <td>1.00</td> </tr> <tr> <th>sigma_gbar</th> <td>0.397</td> <td>0.215</td> <td>0.010</td> <td>0.746</td> <td>0.010</td> <td>0.007</td> <td>470.0</td> <td>470.0</td> <td>355.0</td> <td>157.0</td> <td>1.01</td> </tr> <tr> <th>sigma_g</th> <td>0.460</td> <td>0.031</td> <td>0.402</td> <td>0.519</td> <td>0.001</td> <td>0.000</td> <td>2010.0</td> <td>2010.0</td> <td>2007.0</td> <td>3988.0</td> <td>1.00</td> </tr> <tr> <th>c[0]</th> <td>2.236</td> <td>0.390</td> <td>1.531</td> <td>2.993</td> <td>0.010</td> <td>0.007</td> <td>1432.0</td> <td>1353.0</td> <td>1527.0</td> <td>2343.0</td> <td>1.00</td> </tr> </tbody> </table> </div> ```python az.plot_trace(az_d2_m4, var_names=['gbar']) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_77_0.png) ```python az.summary(az_d2_m4).tail() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mean</th> <th>sd</th> <th>hdi_3%</th> <th>hdi_97%</th> <th>mcse_mean</th> <th>mcse_sd</th> <th>ess_mean</th> <th>ess_sd</th> <th>ess_bulk</th> <th>ess_tail</th> <th>r_hat</th> </tr> </thead> <tbody> <tr> <th>sigma[104]</th> <td>1.038</td> <td>0.141</td> <td>0.764</td> <td>1.294</td> <td>0.002</td> <td>0.001</td> <td>5822.0</td> <td>5822.0</td> <td>5130.0</td> <td>914.0</td> <td>1.0</td> </tr> <tr> <th>sigma[105]</th> <td>0.982</td> <td>0.115</td> <td>0.779</td> <td>1.206</td> <td>0.001</td> <td>0.001</td> <td>6993.0</td> <td>6993.0</td> <td>6701.0</td> <td>894.0</td> <td>1.0</td> </tr> <tr> <th>sigma[106]</th> <td>1.208</td> <td>0.131</td> <td>0.964</td> <td>1.455</td> <td>0.001</td> <td>0.001</td> <td>10173.0</td> <td>9510.0</td> <td>10729.0</td> <td>6237.0</td> <td>1.0</td> </tr> <tr> <th>sigma[107]</th> <td>1.054</td> <td>0.136</td> <td>0.798</td> <td>1.303</td> <td>0.001</td> <td>0.001</td> <td>14240.0</td> <td>13164.0</td> <td>14626.0</td> <td>5427.0</td> <td>1.0</td> </tr> <tr> <th>sigma[108]</th> <td>1.084</td> <td>0.135</td> <td>0.843</td> <td>1.343</td> <td>0.001</td> <td>0.001</td> <td>14609.0</td> <td>13624.0</td> <td>15001.0</td> <td>5716.0</td> <td>1.0</td> </tr> </tbody> </table> </div> ```python az.plot_forest(az_d2_m4, var_names=['sigma'], combined=True) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_79_0.png) ```python az.plot_ppc(az_d2_m4, data_pairs={'y':'y_pred'}, num_pp_samples=100) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_80_0.png) ```python g_jl_post = d2_m4_fit.to_dataframe() \ .melt(id_vars=['chain', 'draw', 'warmup']) \ .pipe(lambda d: d[d.variable.str.contains('g\[')]) ``` ```python g_jl_post.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>chain</th> <th>draw</th> <th>warmup</th> <th>variable</th> <th>value</th> </tr> </thead> <tbody> <tr> <th>1008000</th> <td>0</td> <td>0</td> <td>0</td> <td>g[1,1]</td> <td>-0.430680</td> </tr> <tr> <th>1008001</th> <td>0</td> <td>1</td> <td>0</td> <td>g[1,1]</td> <td>0.238186</td> </tr> <tr> <th>1008002</th> <td>0</td> <td>2</td> <td>0</td> <td>g[1,1]</td> <td>0.170318</td> </tr> <tr> <th>1008003</th> <td>0</td> <td>3</td> <td>0</td> <td>g[1,1]</td> <td>0.149008</td> </tr> <tr> <th>1008004</th> <td>0</td> <td>4</td> <td>0</td> <td>g[1,1]</td> <td>0.331115</td> </tr> </tbody> </table> </div> ```python def extract_g_index(s, i=0, outside_text='g[]'): s_mod = [a.strip(outside_text) for a in s] s_mod = [a.split(',') for a in s_mod] s_mod = [a[i].strip() for a in s_mod] return s_mod ``` ```python g_jl_post = g_jl_post \ .assign(cell_line_idx=lambda x: extract_g_index(x.variable.to_list(), i=0), gene_symbol_idx=lambda x: extract_g_index(x.variable.to_list(), i=1)) \ .astype({'cell_line_idx': int, 'gene_symbol_idx': int}) \ .groupby(['cell_line_idx', 'gene_symbol_idx']) \ .mean() \ .reset_index() \ .astype({'cell_line_idx': int, 'gene_symbol_idx': int}) \ .set_index('cell_line_idx') \ .join(modeling_data[['cell_line', 'cell_line_idx']] \ .drop_duplicates() \ .astype({'cell_line_idx': int}) \ .set_index('cell_line_idx'), how='left') \ .reset_index() \ .set_index('gene_symbol_idx') \ .join(modeling_data[['gene_symbol', 'gene_symbol_idx']] \ .drop_duplicates() \ .astype({'gene_symbol_idx': int}) \ .set_index('gene_symbol_idx'), how='left') \ .reset_index() \ .assign(gene_symbol=lambda x: [f'{a} ({b})' for a,b in zip(x.gene_symbol, x.gene_symbol_idx)], cell_line=lambda x: [f'{a} ({b})' for a,b in zip(x.cell_line, x.cell_line_idx)]) \ .drop(['gene_symbol_idx', 'cell_line_idx'], axis=1) \ .pivot(index='gene_symbol', columns='cell_line', values='value') ``` ```python from scipy.cluster import hierarchy from scipy.spatial import distance ``` ```python # Color bar for tissue of origin of cell lines. cell_line_origin = g_jl_post.columns.to_list() cell_line_origin = [a.split(' ')[0] for a in cell_line_origin] cell_line_origin = [a.split('_')[1:] for a in cell_line_origin] cell_line_origin = [' '.join(a) for a in cell_line_origin] cell_line_pal = sns.husl_palette(len(np.unique(cell_line_origin)), s=.90) cell_line_lut = dict(zip(np.unique(cell_line_origin), cell_line_pal)) cell_line_colors = pd.Series(cell_line_origin, index=g_jl_post.columns).map(cell_line_lut) np.random.seed(123) row_linkage = hierarchy.linkage(distance.pdist(g_jl_post), method='average') p = sns.clustermap(g_jl_post, center=0, cmap="YlGnBu", linewidths=0.5, figsize=(12, 10), cbar_kws={'label': 'mean coeff.'}, cbar_pos=[0.06, 0.15, 0.02, 0.2], row_linkage=row_linkage, col_colors=cell_line_colors) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_86_0.png) ```python d2_m4_post = d2_m4_fit.to_dataframe() ``` ```python genes_post = d2_m4_post.loc[:, d2_m4_post.columns.str.contains('gbar\[')] genes = list(np.unique(modeling_data.gene_symbol)) genes.sort() genes_post.columns = genes for col in genes_post.columns.to_list(): sns.distplot(genes_post[[col]], hist=False, label=col, kde_kws={'shade': False, 'alpha': 0.8}) plt.legend() plt.xlabel('coefficient value') plt.ylabel('density') plt.title('Distribution of coefficients for average gene effect') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_88_0.png) ```python cell_lines_post = d2_m4_post.loc[:, d2_m4_post.columns.str.contains('c\[')] for col in cell_lines_post.columns.to_list(): sns.distplot(cell_lines_post[[col]], hist=False, kde_kws={'shade': False, 'alpha': 0.5}) plt.xlabel('coefficient value') plt.ylabel('density') plt.title('Distribution of coefficients for average shRNA effect') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_89_0.png) ## Model 5. Multiplicative scaling factor of each shRNA In the original DEMETER2 paper, the model includes a multiplicative scaling factor for each shRNA, constrained between 0 and 1, along with the addative varying effect for each shRNA. The factor is multiplied against the gene effect. In this model, I experiment with this multiplicative factor $\alpha_s$. $$ D_{i|s} \sim N(\mu_{i|sjl}, \sigma_s) \\ \mu_{sjl}= c_{s} + \alpha_{s} (\bar g_{l} + g_{jl}) \\ c_s \sim N(0, \sigma_c) \\ \alpha_s \sim \text{Uniform}(0, 1) \\ \bar g_l \sim N(\mu_{\bar g}, \sigma_{\bar g}) \\ g_{jl} \sim N(0, \sigma_g) \\ \sigma_c \sim \text{HalfNormal}(0, 3) \\ \mu_{\bar g} \sim N(0, 2) \quad \sigma_{\bar g} \sim \text{HalfNormal}(0, 10) \\ \sigma_g \sim \text{HalfNormal}(0, 5) \\ \sigma_s \sim \text{HalfNormal}(\mu_\sigma, \sigma_\sigma) \\ \mu_\sigma \sim \text{HalfNormal}(0, 2) \quad \sigma_\sigma \sim \text{HalfNormal}(0, 1) \\ $$ ```python d2_m5_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'L': np.max(modeling_data.gene_symbol_idx), 'J': np.max(modeling_data.cell_line_idx), 'shrna': modeling_data.barcode_sequence_idx, 'gene': modeling_data.gene_symbol_idx, 'cell_line': modeling_data.cell_line_idx, 'y': modeling_data.lfc, } ``` ```python d2_m5_file = models_dir / 'd2_m5.cpp' d2_m5 = StanModel_cache(file=d2_m5_file.as_posix()) ``` Using cached StanModel. ```python d2_m5_control = {'adapt_delta': 0.99, 'max_treedepth': 10} d2_m5_fit = d2_m5.sampling(data=d2_m5_data, iter=3000, warmup=1000, chains=4, control=d2_m5_control) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) WARNING:pystan:5 of 8000 iterations ended with a divergence (0.0625 %). WARNING:pystan:Try running with adapt_delta larger than 0.999 to remove the divergences. WARNING:pystan:5 of 8000 iterations saturated the maximum tree depth of 11 (0.0625 %) WARNING:pystan:Run again with max_treedepth larger than 11 to avoid saturation ```python pystan.check_hmc_diagnostics(d2_m5_fit) ``` WARNING:pystan:2 of 8000 iterations ended with a divergence (0.025 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:2 of 8000 iterations saturated the maximum tree depth of 10 (0.025 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation {'n_eff': True, 'Rhat': True, 'divergence': False, 'treedepth': False, 'energy': True} ```python d2_m5_post = d2_m5_fit.to_dataframe() ``` ```python df = d2_m5_post.loc[:, d2_m5_post.columns.str.contains('alpha\[')] for col in df.columns: sns.distplot(df[[col]], hist=False, kde_kws={'alpha': 0.5}) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_96_0.png) ```python genes_post = d2_m5_post.loc[:, d2_m5_post.columns.str.contains('gbar\[')] genes = list(np.unique(modeling_data.gene_symbol)) genes.sort() genes_post.columns = genes for col in genes_post.columns.to_list(): sns.distplot(genes_post[[col]], hist=False, label=col, kde_kws={'shade': False, 'alpha': 0.8}) plt.legend() plt.xlabel('coefficient value') plt.ylabel('density') plt.title('Distribution of coefficients for average gene effect') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_97_0.png) ```python az_d2_m5 = az.from_pystan(posterior=d2_m5_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m5) az.plot_ppc(az_d2_m5, data_pairs={'y':'y_pred'}, num_pp_samples=100) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_98_0.png) ```python g_jl_post = d2_m5_fit.to_dataframe() \ .melt(id_vars=['chain', 'draw', 'warmup']) \ .pipe(lambda d: d[d.variable.str.contains('g\[')]) ``` ```python g_jl_post = g_jl_post \ .assign(cell_line_idx=lambda x: extract_g_index(x.variable.to_list(), i=0), gene_symbol_idx=lambda x: extract_g_index(x.variable.to_list(), i=1)) \ .astype({'cell_line_idx': int, 'gene_symbol_idx': int}) \ .groupby(['cell_line_idx', 'gene_symbol_idx']) \ .mean() \ .reset_index() \ .astype({'cell_line_idx': int, 'gene_symbol_idx': int}) \ .set_index('cell_line_idx') \ .join(modeling_data[['cell_line', 'cell_line_idx']] \ .drop_duplicates() \ .astype({'cell_line_idx': int}) \ .set_index('cell_line_idx'), how='left') \ .reset_index() \ .set_index('gene_symbol_idx') \ .join(modeling_data[['gene_symbol', 'gene_symbol_idx']] \ .drop_duplicates() \ .astype({'gene_symbol_idx': int}) \ .set_index('gene_symbol_idx'), how='left') \ .reset_index() \ .assign(gene_symbol=lambda x: [f'{a} ({b})' for a,b in zip(x.gene_symbol, x.gene_symbol_idx)], cell_line=lambda x: [f'{a} ({b})' for a,b in zip(x.cell_line, x.cell_line_idx)]) \ .drop(['gene_symbol_idx', 'cell_line_idx'], axis=1) \ .pivot(index='gene_symbol', columns='cell_line', values='value') ``` ```python # Color bar for tissue of origin of cell lines. cell_line_origin = g_jl_post.columns.to_list() cell_line_origin = [a.split(' ')[0] for a in cell_line_origin] cell_line_origin = [a.split('_')[1:] for a in cell_line_origin] cell_line_origin = [' '.join(a) for a in cell_line_origin] cell_line_pal = sns.husl_palette(len(np.unique(cell_line_origin)), s=.90) cell_line_lut = dict(zip(np.unique(cell_line_origin), cell_line_pal)) cell_line_colors = pd.Series(cell_line_origin, index=g_jl_post.columns).map(cell_line_lut) np.random.seed(123) row_linkage = hierarchy.linkage(distance.pdist(g_jl_post), method='average') p = sns.clustermap(g_jl_post, center=0, cmap="YlGnBu", linewidths=0.5, figsize=(12, 10), cbar_kws={'label': 'mean coeff.'}, cbar_pos=[0.06, 0.15, 0.02, 0.2], row_linkage=row_linkage, col_colors=cell_line_colors) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_101_0.png) ```python y_pred = d2_m5_fit.extract(pars='y_pred')['y_pred'] y_pred.shape ``` (8000, 3334) ```python m5_pred_mean = np.apply_along_axis(np.mean, 0, y_pred) m5_pred_hdi = np.apply_along_axis(az.hdi, 0, y_pred, hdi_prob=0.89) d2_m5_pred = pd.DataFrame({ 'pred_mean': m5_pred_mean, 'pred_hdi_low': m5_pred_hdi[0], 'pred_hdi_high': m5_pred_hdi[1], 'obs': d2_m5_data['y'], 'barcode_sequence_idx': d2_m5_data['shrna'], 'gene_idx': d2_m5_data['gene'], 'cell_line_idx': d2_m5_data['cell_line'], 'barcode_sequence': modeling_data.barcode_sequence, 'gene_symbol': modeling_data.gene_symbol, 'cell_line': modeling_data.cell_line, }) d2_m5_pred ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>pred_mean</th> <th>pred_hdi_low</th> <th>pred_hdi_high</th> <th>obs</th> <th>barcode_sequence_idx</th> <th>gene_idx</th> <th>cell_line_idx</th> <th>barcode_sequence</th> <th>gene_symbol</th> <th>cell_line</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.742871</td> <td>-0.748287</td> <td>2.329097</td> <td>0.625725</td> <td>1</td> <td>5</td> <td>11</td> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> <td>efo21_ovary</td> </tr> <tr> <th>1</th> <td>0.779841</td> <td>-0.867941</td> <td>2.339018</td> <td>2.145082</td> <td>1</td> <td>5</td> <td>9</td> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> <td>dbtrg05mg_central_nervous_system</td> </tr> <tr> <th>2</th> <td>0.936184</td> <td>-0.649361</td> <td>2.477397</td> <td>0.932751</td> <td>1</td> <td>5</td> <td>3</td> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> <td>bt20_breast</td> </tr> <tr> <th>3</th> <td>0.876974</td> <td>-0.743851</td> <td>2.407862</td> <td>1.372030</td> <td>1</td> <td>5</td> <td>36</td> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> <td>sw1783_central_nervous_system</td> </tr> <tr> <th>4</th> <td>0.827171</td> <td>-0.709087</td> <td>2.426900</td> <td>0.803835</td> <td>1</td> <td>5</td> <td>18</td> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> <td>kns60_central_nervous_system</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>3329</th> <td>-1.836322</td> <td>-3.815350</td> <td>-0.067366</td> <td>-3.118520</td> <td>109</td> <td>13</td> <td>32</td> <td>TGCTCTCATGGGTCTAGATAT</td> <td>TRIM39</td> <td>shp77_lung</td> </tr> <tr> <th>3330</th> <td>-1.130218</td> <td>-2.953949</td> <td>0.672288</td> <td>-1.858803</td> <td>109</td> <td>13</td> <td>33</td> <td>TGCTCTCATGGGTCTAGATAT</td> <td>TRIM39</td> <td>sknep1_bone</td> </tr> <tr> <th>3331</th> <td>-1.417122</td> <td>-3.211824</td> <td>0.425783</td> <td>-2.398997</td> <td>109</td> <td>13</td> <td>34</td> <td>TGCTCTCATGGGTCTAGATAT</td> <td>TRIM39</td> <td>smsctr_soft_tissue</td> </tr> <tr> <th>3332</th> <td>-0.897946</td> <td>-2.644816</td> <td>0.899824</td> <td>0.948492</td> <td>109</td> <td>13</td> <td>35</td> <td>TGCTCTCATGGGTCTAGATAT</td> <td>TRIM39</td> <td>sudhl4_haematopoietic_and_lymphoid_tissue</td> </tr> <tr> <th>3333</th> <td>-1.335326</td> <td>-3.045359</td> <td>0.599845</td> <td>-2.847713</td> <td>109</td> <td>13</td> <td>37</td> <td>TGCTCTCATGGGTCTAGATAT</td> <td>TRIM39</td> <td>tuhr14tkb_kidney</td> </tr> </tbody> </table> <p>3334 rows × 10 columns</p> </div> ```python genes = list(np.unique(d2_m5_pred.gene_symbol)) genes.sort() fig, axes = plt.subplots(5, 3, figsize=(12, 12)) for ax, gene in zip(axes.flatten(), genes): df = d2_m5_pred[d2_m5_pred.gene_symbol == gene] ax.scatter(df.barcode_sequence, df.obs, color='blue', s=50, alpha=0.2) ax.scatter(df.barcode_sequence, df.pred_mean, color='red', s=20, alpha=0.5) ax.xaxis.set_ticks([]) ax.set_title(gene) axes[4, 2].axis('off') axes[4, 1].axis('off') fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_104_0.png) ```python sns.distplot(d2_m5_pred[d2_m5_pred.gene_symbol == 'KRAS'].obs, label='observed') sns.distplot(d2_m5_pred[d2_m5_pred.gene_symbol == 'KRAS'].pred_mean, label='predicticed') plt.legend() plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_105_0.png) ```python g_pred = d2_m5_fit.to_dataframe() g_pred_cols = g_pred.columns[g_pred.columns.str.contains('g\[')].to_list() g_pred = g_pred[['chain', 'draw', 'warmup'] + g_pred_cols] \ .set_index(['chain', 'draw', 'warmup']) \ .melt() \ .assign(cell_line_idx=lambda x: [int(a) for a in extract_g_index(x.variable)], gene_symbol_idx=lambda x: [int(a) for a in extract_g_index(x.variable, i=1)]) g_pred.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>variable</th> <th>value</th> <th>cell_line_idx</th> <th>gene_symbol_idx</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>g[1,1]</td> <td>-0.072524</td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td>g[1,1]</td> <td>0.342332</td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td>g[1,1]</td> <td>0.187223</td> <td>1</td> <td>1</td> </tr> <tr> <th>3</th> <td>g[1,1]</td> <td>0.253825</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>g[1,1]</td> <td>0.318944</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> ```python cell_line_gene_idx_map = modeling_data \ [['cell_line_idx', 'gene_symbol_idx', 'cell_line', 'gene_symbol']] \ .drop_duplicates() \ .set_index(['cell_line_idx', 'gene_symbol_idx']) cell_line_gene_idx_map.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th></th> <th>cell_line</th> <th>gene_symbol</th> </tr> <tr> <th>cell_line_idx</th> <th>gene_symbol_idx</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>11</th> <th>5</th> <td>efo21_ovary</td> <td>EIF6</td> </tr> <tr> <th>9</th> <th>5</th> <td>dbtrg05mg_central_nervous_system</td> <td>EIF6</td> </tr> <tr> <th>3</th> <th>5</th> <td>bt20_breast</td> <td>EIF6</td> </tr> <tr> <th>36</th> <th>5</th> <td>sw1783_central_nervous_system</td> <td>EIF6</td> </tr> <tr> <th>18</th> <th>5</th> <td>kns60_central_nervous_system</td> <td>EIF6</td> </tr> </tbody> </table> </div> ```python g_pred = g_pred.set_index(['cell_line_idx', 'gene_symbol_idx']) \ .join(cell_line_gene_idx_map, how='left') \ .reset_index() g_pred.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>cell_line_idx</th> <th>gene_symbol_idx</th> <th>variable</th> <th>value</th> <th>cell_line</th> <th>gene_symbol</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>1</td> <td>1</td> <td>g[1,1]</td> <td>-0.072524</td> <td>2313287_stomach</td> <td>BRAF</td> </tr> <tr> <th>1</th> <td>1</td> <td>1</td> <td>g[1,1]</td> <td>0.342332</td> <td>2313287_stomach</td> <td>BRAF</td> </tr> <tr> <th>2</th> <td>1</td> <td>1</td> <td>g[1,1]</td> <td>0.187223</td> <td>2313287_stomach</td> <td>BRAF</td> </tr> <tr> <th>3</th> <td>1</td> <td>1</td> <td>g[1,1]</td> <td>0.253825</td> <td>2313287_stomach</td> <td>BRAF</td> </tr> <tr> <th>4</th> <td>1</td> <td>1</td> <td>g[1,1]</td> <td>0.318944</td> <td>2313287_stomach</td> <td>BRAF</td> </tr> </tbody> </table> </div> ```python kras_muts = pd.read_csv(modeling_data_dir / 'kras_mutants.csv') \ .assign(cell_line=lambda x: [a.lower() for a in x.cell_line]) kras_muts ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>cell_line</th> <th>protein_change</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>a427_lung</td> <td>p.G12D</td> </tr> <tr> <th>1</th> <td>a549_lung</td> <td>p.G12S</td> </tr> <tr> <th>2</th> <td>ags_stomach</td> <td>p.G12D</td> </tr> <tr> <th>3</th> <td>amo1_haematopoietic_and_lymphoid_tissue</td> <td>p.A146T</td> </tr> <tr> <th>4</th> <td>aspc1_pancreas</td> <td>p.G12D</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> </tr> <tr> <th>109</th> <td>sw948_large_intestine</td> <td>p.Q61L</td> </tr> <tr> <th>110</th> <td>tccpan2_pancreas</td> <td>p.G12R</td> </tr> <tr> <th>111</th> <td>tov21g_ovary</td> <td>p.G13C</td> </tr> <tr> <th>112</th> <td>umuc3_urinary_tract</td> <td>p.G12C</td> </tr> <tr> <th>113</th> <td>yd8_upper_aerodigestive_tract</td> <td>p.G138V</td> </tr> </tbody> </table> <p>114 rows × 2 columns</p> </div> ```python def violin_by_cell_line(target_gene, mut_gene, mut_cell_lines): df = g_pred.pipe(lambda x: x[x.gene_symbol == target_gene]) cell_line_order = df.groupby('cell_line').mean().sort_values('value').reset_index().cell_line.to_list() df = df.set_index('cell_line').loc[cell_line_order].reset_index() df = df.assign(mut=lambda x: x.cell_line.isin(mut_cell_lines)) fig = plt.figure(figsize=(15, 5)) plt.axhline(y=0, c='k', alpha=0.4, ls='--') sns.violinplot('cell_line', 'value', hue='mut', data=df, dodge=False) plt.xticks(rotation=60, ha='right') plt.title(f'{target_gene} essentiality for {mut_gene} mutant cell lines') plt.xlabel(None) plt.ylabel('gene effect coeff.') plt.legend(title=f'{mut_gene} mut.') plt.show() ``` ```python violin_by_cell_line('KRAS', 'KRAS', kras_muts.cell_line) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_111_0.png) ```python mutation_data = pd.read_csv(modeling_data_dir / 'ccle_mutations.csv') \ .assign(cell_line=lambda x: [a.lower() for a in x.tumor_sample_barcode]) \ .pipe(lambda x: x[x.cell_line.isin(g_pred.cell_line)]) \ .reset_index(drop=True) mutation_data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>tumor_sample_barcode</th> <th>hugo_symbol</th> <th>chromosome</th> <th>start_position</th> <th>end_position</th> <th>variant_classification</th> <th>variant_type</th> <th>protein_change</th> <th>cell_line</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>CADOES1_BONE</td> <td>NPHP4</td> <td>1</td> <td>5935092</td> <td>5935092</td> <td>Silent</td> <td>SNP</td> <td>p.T962T</td> <td>cadoes1_bone</td> </tr> <tr> <th>1</th> <td>CADOES1_BONE</td> <td>CHD5</td> <td>1</td> <td>6202224</td> <td>6202224</td> <td>De_novo_Start_OutOfFrame</td> <td>SNP</td> <td>NaN</td> <td>cadoes1_bone</td> </tr> <tr> <th>2</th> <td>CADOES1_BONE</td> <td>SLC45A1</td> <td>1</td> <td>8404071</td> <td>8404071</td> <td>Nonstop_Mutation</td> <td>SNP</td> <td>p.*749R</td> <td>cadoes1_bone</td> </tr> <tr> <th>3</th> <td>CADOES1_BONE</td> <td>PRAMEF10</td> <td>1</td> <td>12954514</td> <td>12954514</td> <td>Missense_Mutation</td> <td>SNP</td> <td>p.P257S</td> <td>cadoes1_bone</td> </tr> <tr> <th>4</th> <td>CADOES1_BONE</td> <td>NBPF1</td> <td>1</td> <td>16892276</td> <td>16892276</td> <td>Silent</td> <td>SNP</td> <td>p.A972A</td> <td>cadoes1_bone</td> </tr> </tbody> </table> </div> ```python braf_muts = mutation_data.pipe(lambda x: x[x.hugo_symbol == 'BRAF']) violin_by_cell_line('BRAF', 'BRAF', braf_muts.cell_line) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_113_0.png) ```python egfr_muts = mutation_data.pipe(lambda x: x[x.hugo_symbol == 'EGFR']).cell_line.to_list() violin_by_cell_line('BRAF', 'KRAS and EGFR', kras_muts.cell_line.to_list() + egfr_muts) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_114_0.png) **TODO: look at effect of the multiplicative scaling factor. Maybe compare results with model 4 where there is no multiplicative factor.** ```python d2_m4_fit.model_pars ``` ['sigma_c', 'mu_gbar', 'sigma_gbar', 'sigma_g', 'c', 'gbar', 'g', 'mu_sigma', 'sigma_sigma', 'sigma', 'y_pred'] ```python d2_m5_fit.model_pars ``` ['sigma_c', 'mu_gbar', 'sigma_gbar', 'sigma_g', 'c', 'alpha', 'gbar', 'g', 'mu_sigma', 'sigma_sigma', 'sigma', 'y_pred'] ```python m4_cl_data = d2_m4_fit.extract(pars='c') cl_data = {'m4_c': m4_cl_data['c'].mean(axis=0)} ``` ```python m5_cl_data = d2_m5_fit.extract(pars=['c', 'alpha']) for key, val in m5_cl_data.items(): cl_data[f'm5_{key}'] = val.mean(axis=0) ``` ```python cl_df = pd.DataFrame(cl_data) cl_df.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>m4_c</th> <th>m5_c</th> <th>m5_alpha</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2.235566</td> <td>1.388940</td> <td>0.226152</td> </tr> <tr> <th>1</th> <td>0.848993</td> <td>0.355141</td> <td>0.306266</td> </tr> <tr> <th>2</th> <td>0.703887</td> <td>0.636358</td> <td>0.487371</td> </tr> <tr> <th>3</th> <td>1.265645</td> <td>0.658361</td> <td>0.178976</td> </tr> <tr> <th>4</th> <td>-0.575790</td> <td>0.103500</td> <td>0.775101</td> </tr> </tbody> </table> </div> ```python x_vals = np.linspace(np.min(cl_df.m4_c), np.max(cl_df.m4_c)) sns.scatterplot(x='m4_c', y='m5_c', size='m5_alpha', hue='m5_alpha', data=cl_df, sizes=(50, 150), alpha=0.8, legend='brief') plt.plot(x_vals, x_vals, 'k--', alpha=0.5) plt.xlabel('model 4 cell line intercept') plt.ylabel('model 5 cell line intercept') plt.title('Cell line varying intercepts between models 4 and 5') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_121_0.png) ```python def extract_prediction_info(fit, name): p = fit.extract('y_pred')['y_pred'] p_hdi = np.apply_along_axis(az.hdi, axis=0, arr=p, hdi_prob=0.89) return { f'{name}_pred_mean': p.mean(axis=0), f'{name}_pred_hdi_dn': p_hdi[0], f'{name}_pred_hdi_up': p_hdi[1], } ``` ```python model_predictions = pd.DataFrame({ **extract_prediction_info(d2_m4_fit, "m4"), **extract_prediction_info(d2_m5_fit, "m5"), 'obs': modeling_data.lfc, 'cell_line': modeling_data.cell_line, 'gene_symbol': modeling_data.gene_symbol, 'barcode_sequence': modeling_data.barcode_sequence, }) ``` ```python model_predictions.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>m4_pred_mean</th> <th>m4_pred_hdi_dn</th> <th>m4_pred_hdi_up</th> <th>m5_pred_mean</th> <th>m5_pred_hdi_dn</th> <th>m5_pred_hdi_up</th> <th>obs</th> <th>cell_line</th> <th>gene_symbol</th> <th>barcode_sequence</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.798723</td> <td>-0.811882</td> <td>2.299739</td> <td>0.742871</td> <td>-0.748287</td> <td>2.329097</td> <td>0.625725</td> <td>efo21_ovary</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>1</th> <td>1.015390</td> <td>-0.580458</td> <td>2.510070</td> <td>0.779841</td> <td>-0.867941</td> <td>2.339018</td> <td>2.145082</td> <td>dbtrg05mg_central_nervous_system</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>2</th> <td>1.047552</td> <td>-0.572622</td> <td>2.584981</td> <td>0.936184</td> <td>-0.649361</td> <td>2.477397</td> <td>0.932751</td> <td>bt20_breast</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>3</th> <td>1.143413</td> <td>-0.416845</td> <td>2.732953</td> <td>0.876974</td> <td>-0.743851</td> <td>2.407862</td> <td>1.372030</td> <td>sw1783_central_nervous_system</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>4</th> <td>0.994660</td> <td>-0.538631</td> <td>2.604680</td> <td>0.827171</td> <td>-0.709087</td> <td>2.426900</td> <td>0.803835</td> <td>kns60_central_nervous_system</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> </tbody> </table> </div> ```python genes = np.unique(model_predictions.gene_symbol.astype('string').to_list()) genes.sort() genes model_predictions = model_predictions \ .set_index('gene_symbol') \ .loc[genes] \ .reset_index() \ .reset_index() ``` ```python plt.figure(figsize=(15, 5)) sns.scatterplot(x='index', y='obs', hue='gene_symbol', data=model_predictions) plt.xlabel('shRNA index') plt.ylabel('observed LFC') plt.xlim(-10, len(model_predictions)+10) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_126_0.png) ```python fig, axes = plt.subplots(5, 3, figsize=(10, 15)) for ax, gene in zip(axes.flatten(), genes): df = model_predictions[model_predictions.gene_symbol == gene] ax.scatter(x=df.m4_pred_mean, y=df.m5_pred_mean, alpha=0.5, s=10, color='#5d877b') ax.set_title(gene) axes[4, 2].axis('off') axes[4, 1].axis('off') fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_127_0.png) ```python def abline(ax, slope, intercept): """Plot a line from slope and intercept""" x_vals = np.array(ax.get_xlim()) y_vals = intercept + slope * x_vals ax.plot(x_vals, y_vals, '--') ``` ```python fig, axes = plt.subplots(len(genes), 2, figsize=(8, 35)) for i, gene in enumerate(genes): df = model_predictions[model_predictions.gene_symbol == gene] for j, m in enumerate(('m4', 'm5')): axes[i, j].scatter(df.loc[:, 'obs'], df.loc[:, f'{m}_pred_mean'], c='#a86f7a', s=10, alpha=0.7) abline(axes[i, j], 1, 0) axes[i, j].set_title(f'{gene} ({m})', fontsize=15) axes[i, j].set_xlabel('observed', fontsize=12) axes[i, j].set_ylabel('predicted', fontsize=12) fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_129_0.png) ```python ``` ## Model 6. Multiplicative scaling factor and varying intercept for each cell line There are two new parameters in this model: $a_j$, a varying intercept per cell line, and $\gamma_j$, a multiplicative scaling factor for each cell line. $$ D_{i|sjl} \sim N(\mu_{i|sjl}, \sigma_s) \\ \mu_{sjl} = a_j + \gamma_j(c_{s} + \alpha_s (\bar g_{l} + g_{jl})) \\ a_j \sim N(0, \sigma_a) \\ \gamma_j \sim N(1, 2) \\ c_s \sim N(0, \sigma_c) \\ \alpha_s \sim \text{Uniform}(0, 1) \\ \bar g_l \sim N(\mu_{\bar g}, \sigma_{\bar g}) \\ g_{jl} \sim N(0, \sigma_g) \\ \sigma_a \sim \text{HalfNormal}(2, 3) \\ \sigma_c \sim \text{HalfNormal}(0, 3) \\ \mu_{\bar g} \sim N(0, 2) \quad \sigma_{\bar g} \sim \text{HalfNormal}(0, 10) \\ \sigma_g \sim \text{HalfNormal}(0, 5) \\ \sigma_s \sim \text{HalfNormal}(\mu_\sigma, \sigma_\sigma) \\ \mu_\sigma \sim \text{HalfNormal}(0, 2) \quad \sigma_\sigma \sim \text{HalfNormal}(0, 1) \\ $$ ```python d2_m6_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'L': np.max(modeling_data.gene_symbol_idx), 'J': np.max(modeling_data.cell_line_idx), 'shrna': modeling_data.barcode_sequence_idx, 'gene': modeling_data.gene_symbol_idx, 'cell_line': modeling_data.cell_line_idx, 'y': modeling_data.lfc, } ``` ```python d2_m6_file = models_dir / 'd2_m6.cpp' d2_m6 = StanModel_cache(file=d2_m6_file.as_posix()) ``` INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_66c65136081b1616d9b674dc89996d94 NOW. No cached model - compiling '../models/d2_m6.cpp'. 0.78 minutes to compile model ```python d2_m6_control = {'adapt_delta': 0.99, 'max_treedepth': 10} d2_m6_fit = d2_m6.sampling(data=d2_m6_data, iter=3000, warmup=1000, chains=4, control=d2_m6_control) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) WARNING:pystan:16 of 8000 iterations ended with a divergence (0.2 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:22 of 8000 iterations saturated the maximum tree depth of 10 (0.275 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation WARNING:pystan:Chain 1: E-BFMI = 0.145 WARNING:pystan:Chain 2: E-BFMI = 0.0844 WARNING:pystan:Chain 3: E-BFMI = 0.154 WARNING:pystan:Chain 4: E-BFMI = 0.173 WARNING:pystan:E-BFMI below 0.2 indicates you may need to reparameterize your model ```python pystan.check_hmc_diagnostics(d2_m6_fit) ``` WARNING:pystan:n_eff / iter below 0.001 indicates that the effective sample size has likely been overestimated WARNING:pystan:Rhat above 1.1 or below 0.9 indicates that the chains very likely have not mixed WARNING:pystan:16 of 8000 iterations ended with a divergence (0.2 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:22 of 8000 iterations saturated the maximum tree depth of 10 (0.275 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation WARNING:pystan:Chain 1: E-BFMI = 0.145 WARNING:pystan:Chain 2: E-BFMI = 0.0844 WARNING:pystan:Chain 3: E-BFMI = 0.154 WARNING:pystan:Chain 4: E-BFMI = 0.173 WARNING:pystan:E-BFMI below 0.2 indicates you may need to reparameterize your model {'n_eff': False, 'Rhat': False, 'divergence': False, 'treedepth': False, 'energy': False} ```python d2_m6_post = d2_m6_fit.to_dataframe() ``` ```python df = d2_m6_post.loc[:, d2_m6_post.columns.str.contains('alpha\[')] for col in df.columns: sns.distplot(df[[col]], hist=False, kde_kws={'alpha': 0.5}) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_137_0.png) ```python df = d2_m6_post.loc[:, d2_m6_post.columns.str.contains('gamma\[')] for col in df.columns: sns.distplot(df[[col]], hist=False, kde_kws={'alpha': 0.5}) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_138_0.png) ```python genes_post = d2_m6_post.loc[:, d2_m6_post.columns.str.contains('gbar\[')] genes = list(np.unique(modeling_data.gene_symbol)) genes.sort() genes_post.columns = genes for col in genes_post.columns.to_list(): sns.distplot(genes_post[[col]], hist=False, label=col, kde_kws={'shade': False, 'alpha': 0.8}) plt.legend() plt.xlabel('coefficient value') plt.ylabel('density') plt.title('Distribution of coefficients for average gene effect') plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_139_0.png) ```python az_d2_m6 = az.from_pystan(posterior=d2_m6_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m6) az.plot_ppc(az_d2_m6, data_pairs={'y':'y_pred'}, num_pp_samples=100) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_140_0.png) ## Model 7. Only a varying intercept for each cell line (no scaling factor) The previous model had difficult fiting. This model removes the per-cell-line scaling factor, leaving the parameter for varying effects per cell line. $$ D_{i|sjl} \sim N(\mu_{i|sjl}, \sigma_s) \\ \mu_{sjl} = a_j + c_{s} + \alpha_s (\bar g_{l} + g_{jl}) \\ a_j \sim N(0, \sigma_a) \\ c_s \sim N(0, \sigma_c) \\ \alpha_s \sim \text{Uniform}(0, 1) \\ \bar g_l \sim N(\mu_{\bar g}, \sigma_{\bar g}) \\ g_{jl} \sim N(0, \sigma_g) \\ \sigma_a \sim \text{HalfNormal}(0, 2) \\ \sigma_c \sim \text{HalfNormal}(0, 3) \\ \mu_{\bar g} \sim N(0, 2) \quad \sigma_{\bar g} \sim \text{HalfNormal}(0, 3) \\ \sigma_g \sim \text{HalfNormal}(0, 3) \\ \sigma_s \sim \text{HalfNormal}(\mu_\sigma, \sigma_\sigma) \\ \mu_\sigma \sim \text{HalfNormal}(0, 2) \quad \sigma_\sigma \sim \text{HalfNormal}(0, 1) \\ $$ ```python d2_m7_data = { 'N': int(modeling_data.shape[0]), 'S': np.max(modeling_data.barcode_sequence_idx), 'L': np.max(modeling_data.gene_symbol_idx), 'J': np.max(modeling_data.cell_line_idx), 'shrna': modeling_data.barcode_sequence_idx, 'gene': modeling_data.gene_symbol_idx, 'cell_line': modeling_data.cell_line_idx, 'y': modeling_data.lfc, } ``` ```python d2_m7_file = models_dir / 'd2_m7.cpp' d2_m7 = StanModel_cache(file=d2_m7_file.as_posix()) ``` Using cached StanModel. ```python d2_m7_control = {'adapt_delta': 0.99, 'max_treedepth': 10} d2_m7_fit = d2_m7.sampling(data=d2_m7_data, iter=3000, warmup=1000, chains=4, control=d2_m7_control, n_jobs=5) ``` WARNING:pystan:Maximum (flat) parameter count (1000) exceeded: skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit) WARNING:pystan:1 of 8000 iterations ended with a divergence (0.0125 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:1 of 8000 iterations saturated the maximum tree depth of 10 (0.0125 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation ```python pystan.check_hmc_diagnostics(d2_m7_fit) ``` WARNING:pystan:1 of 8000 iterations ended with a divergence (0.0125 %). WARNING:pystan:Try running with adapt_delta larger than 0.99 to remove the divergences. WARNING:pystan:1 of 8000 iterations saturated the maximum tree depth of 10 (0.0125 %) WARNING:pystan:Run again with max_treedepth larger than 10 to avoid saturation {'n_eff': True, 'Rhat': True, 'divergence': False, 'treedepth': False, 'energy': True} ```python d2_m7_post = d2_m7_fit.to_dataframe() ``` ```python az_d2_m7 = az.from_pystan(posterior=d2_m7_fit, posterior_predictive='y_pred', observed_data=['y'], posterior_model=d2_m7) az.plot_ppc(az_d2_m7, data_pairs={'y':'y_pred'}, num_pp_samples=100) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_147_0.png) ```python d2_m7_a_post = pd.DataFrame(d2_m7_fit.extract('a')['a']) cell_line_map = modeling_data[['cell_line', 'cell_line_idx']] \ .drop_duplicates() \ .sort_values('cell_line_idx') \ .reset_index(drop=True) d2_m7_a_post.columns = cell_line_map.cell_line ``` ```python for cell_line in d2_m7_a_post.columns.to_list(): sns.distplot(d2_m7_a_post[[cell_line]], hist=False, kde_kws={'alpha': 0.5}) ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_149_0.png) ```python d2_m7_pred = pd.DataFrame(d2_m7_fit.extract('y_pred')['y_pred']) d2_m7_pred.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>...</th> <th>3324</th> <th>3325</th> <th>3326</th> <th>3327</th> <th>3328</th> <th>3329</th> <th>3330</th> <th>3331</th> <th>3332</th> <th>3333</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2.135660</td> <td>0.414827</td> <td>0.334429</td> <td>1.169825</td> <td>0.730670</td> <td>2.100070</td> <td>-0.097630</td> <td>0.825503</td> <td>0.811204</td> <td>0.886321</td> <td>...</td> <td>-1.271522</td> <td>-1.604833</td> <td>-0.681266</td> <td>-2.412664</td> <td>-0.092858</td> <td>-1.769742</td> <td>-1.023952</td> <td>-1.709334</td> <td>-1.446946</td> <td>-1.867585</td> </tr> <tr> <th>1</th> <td>-0.258568</td> <td>1.589077</td> <td>0.975810</td> <td>2.683896</td> <td>1.944490</td> <td>2.222514</td> <td>-0.369773</td> <td>0.907256</td> <td>1.329136</td> <td>1.167455</td> <td>...</td> <td>-3.554992</td> <td>0.909750</td> <td>-1.305267</td> <td>-0.659696</td> <td>-0.430644</td> <td>-1.464651</td> <td>-0.405352</td> <td>-3.262250</td> <td>-0.406125</td> <td>-2.403691</td> </tr> <tr> <th>2</th> <td>0.991447</td> <td>0.995235</td> <td>0.319739</td> <td>0.829170</td> <td>0.861540</td> <td>1.489871</td> <td>-0.840679</td> <td>1.842453</td> <td>0.537677</td> <td>1.225023</td> <td>...</td> <td>0.159416</td> <td>-1.171176</td> <td>-1.501274</td> <td>-2.026308</td> <td>-1.028868</td> <td>-1.797697</td> <td>-0.161722</td> <td>-0.608210</td> <td>-1.747198</td> <td>-0.662055</td> </tr> <tr> <th>3</th> <td>1.359276</td> <td>1.887486</td> <td>2.536779</td> <td>2.099641</td> <td>0.495947</td> <td>0.421383</td> <td>0.522812</td> <td>0.178429</td> <td>0.001630</td> <td>2.200154</td> <td>...</td> <td>-2.485514</td> <td>0.115954</td> <td>-0.794616</td> <td>-1.327708</td> <td>-0.756625</td> <td>-1.725587</td> <td>-4.247362</td> <td>-1.169149</td> <td>-0.628886</td> <td>0.604209</td> </tr> <tr> <th>4</th> <td>0.403651</td> <td>-0.367544</td> <td>0.098439</td> <td>0.566884</td> <td>1.336703</td> <td>0.360488</td> <td>-1.058102</td> <td>1.923034</td> <td>0.040789</td> <td>2.334603</td> <td>...</td> <td>-2.767285</td> <td>-2.070522</td> <td>-2.672827</td> <td>-2.081729</td> <td>-0.788420</td> <td>-2.484335</td> <td>-1.050932</td> <td>-1.563766</td> <td>-1.309522</td> <td>-0.289561</td> </tr> </tbody> </table> <p>5 rows × 3334 columns</p> </div> ```python d2_m7_pred_mean = d2_m7_pred \ .melt(var_name='data_pt') \ .groupby('data_pt') \ .mean() d2_m7_pred_mean['hdi'] = d2_m7_pred.apply(axis=1, func=lambda x: az.hdi(np.array(x))) d2_m7_pred_mean = d2_m7_pred_mean \ .assign(hdi_dn=lambda x: [a[0] for a in x.hdi], hdi_up=lambda x: [a[1] for a in x.hdi]) \ .reset_index() d2_m7_pred_mean['gene_symbol_idx'] = d2_m7_data['gene'] d2_m7_pred_mean['barcode_sequence_idx'] = d2_m7_data['shrna'] d2_m7_pred_mean = pd.merge( d2_m7_pred_mean, modeling_data[['gene_symbol', 'gene_symbol_idx']].drop_duplicates(), how='left', on='gene_symbol_idx' ) d2_m7_pred_mean = pd.merge( d2_m7_pred_mean, modeling_data[['barcode_sequence', 'barcode_sequence_idx']].drop_duplicates(), how='left', on='barcode_sequence_idx' ) d2_m7_pred_mean.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>data_pt</th> <th>value</th> <th>hdi</th> <th>hdi_dn</th> <th>hdi_up</th> <th>gene_symbol_idx</th> <th>barcode_sequence_idx</th> <th>gene_symbol</th> <th>barcode_sequence</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0</td> <td>1.327296</td> <td>[-4.596127267026097, 1.7751894749567059]</td> <td>-4.596127</td> <td>1.775189</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>1</th> <td>1</td> <td>0.244436</td> <td>[-4.5335408181883485, 1.9609086301908234]</td> <td>-4.533541</td> <td>1.960909</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>2</th> <td>2</td> <td>0.991050</td> <td>[-4.41952942019391, 1.9664193474126457]</td> <td>-4.419529</td> <td>1.966419</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>3</th> <td>3</td> <td>0.960443</td> <td>[-4.723445979399989, 1.7270904559989635]</td> <td>-4.723446</td> <td>1.727090</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>4</th> <td>4</td> <td>1.039913</td> <td>[-4.578403632973594, 1.648208253996473]</td> <td>-4.578404</td> <td>1.648208</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> </tbody> </table> </div> ```python fig, axes = plt.subplots(5, 3, figsize=(12, 20)) genes = np.unique(d2_m7_pred_mean.sort_values('gene_symbol').gene_symbol.to_list()) for ax, gene in zip(axes.flatten(), genes): g_data = d2_m7_pred_mean[d2_m7_pred_mean.gene_symbol == gene] \ .reset_index(drop=True) \ .reset_index() for i in range(len(g_data)): ax.plot((i, i), (g_data.hdi_dn[i], d2_m7_pred_mean.hdi_up[i]), c='#c9c9c9', alpha=0.5) sns.scatterplot(x='index', y='value', hue='barcode_sequence', data=g_data, legend=False, ax=ax) ax.set_title(gene, fontsize=12) axes[4, 2].axis('off') axes[4, 1].axis('off') fig.tight_layout(pad=1.0) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_152_0.png) ```python d2_m7_pred_mean ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>data_pt</th> <th>value</th> <th>hdi</th> <th>hdi_dn</th> <th>hdi_up</th> <th>gene_symbol_idx</th> <th>barcode_sequence_idx</th> <th>gene_symbol</th> <th>barcode_sequence</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0</td> <td>1.327296</td> <td>[-4.596127267026097, 1.7751894749567059]</td> <td>-4.596127</td> <td>1.775189</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>1</th> <td>1</td> <td>0.244436</td> <td>[-4.5335408181883485, 1.9609086301908234]</td> <td>-4.533541</td> <td>1.960909</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>2</th> <td>2</td> <td>0.991050</td> <td>[-4.41952942019391, 1.9664193474126457]</td> <td>-4.419529</td> <td>1.966419</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>3</th> <td>3</td> <td>0.960443</td> <td>[-4.723445979399989, 1.7270904559989635]</td> <td>-4.723446</td> <td>1.727090</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>4</th> <td>4</td> <td>1.039913</td> <td>[-4.578403632973594, 1.648208253996473]</td> <td>-4.578404</td> <td>1.648208</td> <td>5</td> <td>1</td> <td>EIF6</td> <td>ACAGAAGAAATTCTGGCAGAT</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>3329</th> <td>3329</td> <td>-1.649936</td> <td>[-4.585495669287962, 1.7745792535842833]</td> <td>-4.585496</td> <td>1.774579</td> <td>13</td> <td>109</td> <td>TRIM39</td> <td>TGCTCTCATGGGTCTAGATAT</td> </tr> <tr> <th>3330</th> <td>3330</td> <td>-1.139632</td> <td>[-4.292058452422176, 2.0046199948082952]</td> <td>-4.292058</td> <td>2.004620</td> <td>13</td> <td>109</td> <td>TRIM39</td> <td>TGCTCTCATGGGTCTAGATAT</td> </tr> <tr> <th>3331</th> <td>3331</td> <td>-1.293152</td> <td>[-4.616257206899434, 1.939295593995174]</td> <td>-4.616257</td> <td>1.939296</td> <td>13</td> <td>109</td> <td>TRIM39</td> <td>TGCTCTCATGGGTCTAGATAT</td> </tr> <tr> <th>3332</th> <td>3332</td> <td>-1.042668</td> <td>[-4.399500114545466, 1.695579964952048]</td> <td>-4.399500</td> <td>1.695580</td> <td>13</td> <td>109</td> <td>TRIM39</td> <td>TGCTCTCATGGGTCTAGATAT</td> </tr> <tr> <th>3333</th> <td>3333</td> <td>-1.509146</td> <td>[-4.35022691859504, 2.0816350404236923]</td> <td>-4.350227</td> <td>2.081635</td> <td>13</td> <td>109</td> <td>TRIM39</td> <td>TGCTCTCATGGGTCTAGATAT</td> </tr> </tbody> </table> <p>3334 rows × 9 columns</p> </div> ```python plt.scatter(x=d2_m7_pred_mean.loc[:, 'value'], y=d2_m7_data['y']) plt.show() ``` ![png](005_demeter2-in-stan_files/005_demeter2-in-stan_154_0.png) ```python ``` <file_sep>data { int<lower=0> N; // number of data points vector[N] y; // LFC data } parameters { real alpha; // intercept real<lower=0> sigma; // standard deviation } model { // Priors alpha ~ normal(0, 5); sigma ~ cauchy(0, 5); y ~ normal(alpha, sigma); } generated quantities { vector[N] y_pred; for (n in 1:N) y_pred[n] = normal_rng(alpha, sigma); }<file_sep># Data preparation ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from pathlib import Path import janitor plt.style.use('seaborn-whitegrid') plt.rcParams['figure.figsize'] = (8.0, 5.0) plt.rcParams['axes.titlesize'] = 18 plt.rcParams['axes.labelsize'] = 15 data_dir = Path('../data') ``` ## shRNA mapping ```python shrna_mapping_df = pd.read_csv(data_dir / 'shRNAmapping.csv').clean_names() shrna_mapping_df.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>gene_symbol</th> <th>gene_id</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>AAAAATGGCATCAACCACCAT</td> <td>RPS6KA1</td> <td>6195</td> </tr> <tr> <th>1</th> <td>AAAACCGTGGACTTCAAGAAG</td> <td>NO_CURRENT_1</td> <td>NO_CURRENT_1</td> </tr> <tr> <th>2</th> <td>AAAAGGATAACCCAGGTGTTT</td> <td>TSC1</td> <td>7248</td> </tr> <tr> <th>3</th> <td>AAAAGTGAGGACAATCCGCAA</td> <td>RAPGEFL1</td> <td>51195</td> </tr> <tr> <th>4</th> <td>AAAATCAGTCATGGTGATTTA</td> <td>CECR2</td> <td>27443</td> </tr> </tbody> </table> </div> ## Knock-down data ```python def load_achilles_lfc_data(fpath): df = pd.read_csv(data_dir / fpath) \ .clean_names() \ .rename({'unnamed_0': 'barcode_sequence'}, axis=1) \ .melt(id_vars=['barcode_sequence'], var_name='cell_line', value_name='lfc') return df ``` ```python achilles_55k_batch1_lfc = load_achilles_lfc_data('achilles55kbatch1repcollapsedlfc.csv') achilles_55k_batch1_lfc.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ATATCCACCACTTTAACCTTA</td> <td>ln215_central_nervous_system</td> <td>-1.896471</td> </tr> <tr> <th>1</th> <td>GACAACAGACAAATCACCATT</td> <td>ln215_central_nervous_system</td> <td>-0.364165</td> </tr> <tr> <th>2</th> <td>GCCAGTGATTATGAGCTTGAA</td> <td>ln215_central_nervous_system</td> <td>-2.744832</td> </tr> <tr> <th>3</th> <td>GCTAAGTACAGGGCCAAGTTT</td> <td>ln215_central_nervous_system</td> <td>1.621193</td> </tr> <tr> <th>4</th> <td>AGAGCTGTTTGACCGGATAGT</td> <td>ln215_central_nervous_system</td> <td>-2.154795</td> </tr> </tbody> </table> </div> ```python achilles_55k_batch2_lfc = load_achilles_lfc_data('achilles55kbatch2repcollapsedlfc.csv') achilles_55k_batch2_lfc.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ATATCCACCACTTTAACCTTA</td> <td>ov7_ovary</td> <td>-1.117770</td> </tr> <tr> <th>1</th> <td>GACAACAGACAAATCACCATT</td> <td>ov7_ovary</td> <td>-0.135925</td> </tr> <tr> <th>2</th> <td>CTAGAAAGAGTGCAGAACAAT</td> <td>ov7_ovary</td> <td>-1.932332</td> </tr> <tr> <th>3</th> <td>GCCAGTGATTATGAGCTTGAA</td> <td>ov7_ovary</td> <td>-1.145431</td> </tr> <tr> <th>4</th> <td>GCTAAGTACAGGGCCAAGTTT</td> <td>ov7_ovary</td> <td>0.441416</td> </tr> </tbody> </table> </div> ```python achilles_98k_lfc = load_achilles_lfc_data('achilles98krepcollapsedlfc.csv') achilles_98k_lfc.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>AAAAATGGCATCAACCACCAT</td> <td>143b_bone</td> <td>-0.146756</td> </tr> <tr> <th>1</th> <td>AAACACATTTGGGATGTTCCT</td> <td>143b_bone</td> <td>1.170334</td> </tr> <tr> <th>2</th> <td>AAAGAAGAAGCTGCAATATCT</td> <td>143b_bone</td> <td>1.490805</td> </tr> <tr> <th>3</th> <td>AAGCGTGCCGTAGACTGTCCA</td> <td>143b_bone</td> <td>0.543632</td> </tr> <tr> <th>4</th> <td>AATCTAAGAGAGCTGCCATCG</td> <td>143b_bone</td> <td>0.172294</td> </tr> </tbody> </table> </div> ## Original DEMETER2 results ```python def extract_gene_name(df): gene_names = [a.split(' ', 1)[0] for a in df['gene']] df['gene'] = gene_names return df ``` ```python d2_res_path = Path('../data/D2_Achilles_gene_dep_scores.csv') d2_res_df = pd.read_csv(d2_res_path) \ .clean_names() \ .rename({'unnamed_0': 'gene'}, axis=1) \ .pipe(extract_gene_name) d2_res_df.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>gene</th> <th>143b_bone</th> <th>22rv1_prostate</th> <th>2313287_stomach</th> <th>697_haematopoietic_and_lymphoid_tissue</th> <th>769p_kidney</th> <th>786o_kidney</th> <th>a1207_central_nervous_system</th> <th>a172_central_nervous_system</th> <th>a204_soft_tissue</th> <th>...</th> <th>wm1799_skin</th> <th>wm2664_skin</th> <th>wm793_skin</th> <th>wm88_skin</th> <th>wm983b_skin</th> <th>yd38_upper_aerodigestive_tract</th> <th>yd8_upper_aerodigestive_tract</th> <th>ykg1_central_nervous_system</th> <th>zr751_breast</th> <th>zr7530_breast</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>A1BG</td> <td>0.052466</td> <td>-0.115242</td> <td>-0.023172</td> <td>-0.023337</td> <td>-0.127913</td> <td>-0.045175</td> <td>-0.180962</td> <td>0.006975</td> <td>-0.017205</td> <td>...</td> <td>-0.116620</td> <td>-0.348762</td> <td>0.015806</td> <td>-0.183945</td> <td>-0.071312</td> <td>0.150626</td> <td>-0.049987</td> <td>0.011004</td> <td>-0.149293</td> <td>-0.167596</td> </tr> <tr> <th>1</th> <td>NAT2</td> <td>0.084173</td> <td>0.000951</td> <td>-0.154188</td> <td>-0.079006</td> <td>-0.162207</td> <td>-0.172578</td> <td>-0.264920</td> <td>-0.174468</td> <td>-0.249258</td> <td>...</td> <td>-0.299439</td> <td>-0.123712</td> <td>-0.121711</td> <td>-0.104603</td> <td>-0.265162</td> <td>0.021261</td> <td>-0.158058</td> <td>0.058858</td> <td>-0.144623</td> <td>0.133460</td> </tr> <tr> <th>2</th> <td>ADA</td> <td>0.207020</td> <td>0.010743</td> <td>-0.072102</td> <td>0.045611</td> <td>-0.002487</td> <td>0.170009</td> <td>-0.000351</td> <td>0.123135</td> <td>-0.054149</td> <td>...</td> <td>0.060647</td> <td>0.080939</td> <td>0.331585</td> <td>0.032316</td> <td>-0.066345</td> <td>0.061082</td> <td>0.126664</td> <td>0.204871</td> <td>-0.202153</td> <td>0.085652</td> </tr> <tr> <th>3</th> <td>CDH2</td> <td>0.062192</td> <td>-0.049809</td> <td>0.022137</td> <td>0.061709</td> <td>-0.063397</td> <td>0.127787</td> <td>-0.184580</td> <td>-0.040643</td> <td>0.203570</td> <td>...</td> <td>-0.071168</td> <td>0.004119</td> <td>-0.013560</td> <td>-0.048310</td> <td>-0.138371</td> <td>-0.036057</td> <td>-0.075598</td> <td>0.012575</td> <td>0.044692</td> <td>-0.055539</td> </tr> <tr> <th>4</th> <td>AKT3</td> <td>0.039280</td> <td>-0.076596</td> <td>0.136445</td> <td>0.154167</td> <td>0.140487</td> <td>0.243081</td> <td>-0.143867</td> <td>-0.026991</td> <td>-0.192979</td> <td>...</td> <td>0.027439</td> <td>-0.117479</td> <td>-0.024036</td> <td>0.119678</td> <td>0.042359</td> <td>0.107166</td> <td>0.159401</td> <td>0.071568</td> <td>0.053298</td> <td>0.021455</td> </tr> </tbody> </table> <p>5 rows × 502 columns</p> </div> ```python d2_res_df.mean().plot.kde() plt.xlabel('average cell line score') plt.title('Distribution of D2 scores per cell line') plt.show() ``` ![png](001_data-preparation_files/001_data-preparation_12_0.png) ```python d2_res_df.set_index('gene').mean(axis=1).plot.kde() plt.xlabel('average gene score') plt.title('Distribution of D2 scores per gene') plt.show() ``` ![png](001_data-preparation_files/001_data-preparation_13_0.png) ```python pd.DataFrame(d2_res_df.set_index('gene').mean(axis=1), columns=['avg_d2_score']) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>avg_d2_score</th> </tr> <tr> <th>gene</th> <th></th> </tr> </thead> <tbody> <tr> <th>A1BG</th> <td>-0.128559</td> </tr> <tr> <th>NAT2</th> <td>-0.062949</td> </tr> <tr> <th>ADA</th> <td>0.052180</td> </tr> <tr> <th>CDH2</th> <td>0.035571</td> </tr> <tr> <th>AKT3</th> <td>0.073588</td> </tr> <tr> <th>...</th> <td>...</td> </tr> <tr> <th>PTBP3</th> <td>-0.656251</td> </tr> <tr> <th>KCNE2</th> <td>-0.003405</td> </tr> <tr> <th>DGCR2</th> <td>0.050086</td> </tr> <tr> <th>CASP8AP2</th> <td>-0.524194</td> </tr> <tr> <th>SCO2</th> <td>-0.076897</td> </tr> </tbody> </table> <p>16755 rows × 1 columns</p> </div> Set of genes where there will be differences across cell lines. ```python specific_test_genes = ['KRAS', 'BRAF', 'EGFR', 'PTK2'] d2_res_df[d2_res_df.gene.isin(specific_test_genes)].set_index('gene').T.plot.kde() plt.xlabel('D2 score') plt.ylabel('density') plt.title('D2 scores for select genes') plt.show() ``` ![png](001_data-preparation_files/001_data-preparation_16_0.png) A set of random genes. ```python num_rand_genes = 10 random_genes = d2_res_df.dropna().sample(n=num_rand_genes, random_state=123) random_genes.set_index('gene').T.plot.kde(legend=None) plt.xlabel('D2 score') plt.ylabel('density') plt.title(f'D2 scores for {num_rand_genes} random genes') plt.show() ``` ![png](001_data-preparation_files/001_data-preparation_18_0.png) Final subset of genes to experiment with. ```python genes_to_model = specific_test_genes + random_genes.gene.to_list() genes_to_model ``` ['KRAS', 'BRAF', 'EGFR', 'PTK2', 'RHBDL2', 'ESPL1', 'LOC105379645&KIR2DL2', 'TRIM39', 'SDHB', 'COL8A1', 'COG3', 'GRK5', 'EIF6', 'RC3H2'] --- ## Modeling data ```python model_data_dir = Path('../modeling_data') ``` ### shRNA ```python model_shrna_mapping = shrna_mapping_df[shrna_mapping_df.gene_symbol.isin(genes_to_model)] model_shrna_mapping = model_shrna_mapping.reset_index(drop=True).drop('gene_id', axis=1) model_shrna_mapping.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>gene_symbol</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>ACAAATCCATTGAGCCTTATT</td> <td>SDHB</td> </tr> <tr> <th>1</th> <td>ACAGAAGAAATTCTGGCAGAT</td> <td>EIF6</td> </tr> <tr> <th>2</th> <td>ACCTCAATAAGGTCTCAAAAT</td> <td>SDHB</td> </tr> <tr> <th>3</th> <td>ACGAGATGATAGAAACAGAAT</td> <td>GRK5</td> </tr> <tr> <th>4</th> <td>ACTGATGTGTGTTAATTATGA</td> <td>BRAF</td> </tr> </tbody> </table> </div> ```python model_shrna_mapping.to_csv(model_data_dir / "shRNA_mapping.csv", index=False) ``` ### Log-fold-change data ```python achilles_55k_batch1_lfc['batch'] = 1 achilles_55k_batch2_lfc['batch'] = 2 achilles_98k_lfc['batch'] = 3 def filter_df_barcodes(df): new_df = df[df.barcode_sequence.isin(model_shrna_mapping.barcode_sequence)] return new_df lfc_data = pd.concat( [filter_df_barcodes(achilles_55k_batch1_lfc), filter_df_barcodes(achilles_55k_batch2_lfc), filter_df_barcodes(achilles_98k_lfc)], ignore_index=True ) lfc_data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>barcode_sequence</th> <th>cell_line</th> <th>lfc</th> <th>batch</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>CCAACCTCAATAAGGTCTCAA</td> <td>ln215_central_nervous_system</td> <td>0.898372</td> <td>1</td> </tr> <tr> <th>1</th> <td>CGCAAGTGTAAGAAGTGCGAA</td> <td>ln215_central_nervous_system</td> <td>-2.754383</td> <td>1</td> </tr> <tr> <th>2</th> <td>GCTCTCTATAGAAGGTTCTTT</td> <td>ln215_central_nervous_system</td> <td>0.589738</td> <td>1</td> </tr> <tr> <th>3</th> <td>GCTGAGAATGTGGAATACCTA</td> <td>ln215_central_nervous_system</td> <td>-1.127432</td> <td>1</td> </tr> <tr> <th>4</th> <td>AGAGAACTTCTACAGTGTGTT</td> <td>ln215_central_nervous_system</td> <td>-1.820344</td> <td>1</td> </tr> </tbody> </table> </div> ```python lfc_data.shape ``` (45703, 4) ```python modeling_data.to_csv(model_data_dir / 'subset_modeling_data.csv', index=False) ``` --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-20-02a7a0fd22a6> in <module> ----> 1 modeling_data.to_csv(model_data_dir / 'subset_modeling_data.csv', index=False) NameError: name 'modeling_data' is not defined ```python ``` <file_sep>data { int<lower=0> N; // number of data points int<lower=1> S; // number of shRNAs int<lower=1, upper=S> shrna[N]; // index shRNA } generated quantities { vector[S] alpha; vector[N] y_pred; real mu_alpha = normal_rng(0, 2.0); real<lower=0> sigma_alpha = abs(cauchy_rng(0, 10.0)); real<lower=0> sigma = abs(cauchy_rng(0, 10.0)); for (s in 1:S) { alpha[s] = normal_rng(mu_alpha, sigma_alpha); } for (n in 1:N) y_pred[n] = normal_rng(alpha[shrna[n]], sigma); } <file_sep>data { int<lower=0> N; // number of data points int<lower=1> S; // number of shRNAs int<lower=1> L; // number of genes int<lower=1> J; // number of cell lines int<lower=1, upper=S> shrna[N]; // shRNA index int<lower=1, upper=L> gene[N]; // gene index int<lower=1, upper=J> cell_line[N]; // cell line index vector[N] y; // LFC data } parameters { real<lower=0> sigma_c; real mu_gbar; real<lower=0> sigma_gbar; real<lower=0> sigma_g; real<lower=0> sigma_a; real a[J]; real c[S]; real<lower=0, upper=1> alpha[S]; real gbar[L]; real g[J,L]; real<lower=0> mu_sigma; real<lower=0> sigma_sigma; real<lower=0> sigma[S]; } model { // Hyperpriors sigma_c ~ normal(0, 3.0); mu_gbar ~ normal(0, 2.0); sigma_gbar ~ normal(0, 3.0); sigma_g ~ normal(0, 3.0); sigma_a ~ normal(0.0, 2.0); mu_sigma ~ normal(0, 2.0); sigma_sigma ~ normal(0, 1.0); // Priors a ~ normal(0, sigma_a); c ~ normal(0, sigma_c); alpha ~ uniform(0, 1); gbar ~ normal(mu_gbar, sigma_gbar); for (l in 1:L) g[,l] ~ normal(0, sigma_g); sigma ~ normal(mu_sigma, sigma_sigma); { vector[N] y_hat; for (n in 1:N) { y_hat[n] = a[cell_line[n]] + c[shrna[n]] + alpha[shrna[n]] * (gbar[gene[n]] + g[cell_line[n], gene[n]]); y[n] ~ normal(y_hat[n], sigma[shrna[n]]); } } } generated quantities { vector[N] y_pred; // Posterior predictions for (n in 1:N) y_pred[n] = normal_rng(a[cell_line[n]] + c[shrna[n]] + alpha[shrna[n]] * (gbar[gene[n]] + g[cell_line[n], gene[n]]), sigma[shrna[n]]); } <file_sep>#!/bin/zsh for ipynb in **/*.ipynb do jupyter nbconvert --to markdown $ipynb done <file_sep>#!/bin/bash module load R/4.0.1 python/3.7.4 # Bash aliases used in this project. alias demeter_srun="srun --pty -p priority --mem 50G -c 5 -t 0-18:00 --x11 /bin/bash" alias demeter_env="conda activate demeter2-stan && bash .proj_aliases.sh" alias demeter_jl="jupyter lab --port=7010 --browser='none'" alias demeter_sshlab='ssh -N -L 7010:127.0.0.1:7010' <file_sep>import pystan import pickle from hashlib import md5 from timeit import default_timer as timer from pathlib import Path def StanModel_cache(file, model_name='anon_model', **kwargs): """Use just as you would `StanModel`""" with open(file) as f: txt = f.read() code_hash = md5(txt.encode('ascii')).hexdigest() cache_fname = Path('cached-stan-models/cached-{}-{}.pkl'.format(model_name, code_hash)) try: sm = pickle.load(open(cache_fname, 'rb')) except: print(f'No cached model - compiling \'{file}\'.') start = timer() sm = pystan.StanModel(file=file, model_name=model_name, **kwargs) end = timer() print(f'{(end - start) / 60:.2f} minutes to compile model') with open(cache_fname, 'wb') as f: pickle.dump(sm, f) else: print('Using cached StanModel.') return sm<file_sep># Preparation of CCLE data ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from pathlib import Path import janitor plt.style.use('seaborn-whitegrid') plt.rcParams['figure.figsize'] = (8.0, 5.0) plt.rcParams['axes.titlesize'] = 18 plt.rcParams['axes.labelsize'] = 15 data_dir = Path('../data') modeling_data_dir = Path('../modeling_data') ``` ```python mutation_df = pd.read_csv(data_dir / 'CCLE_mutation_data.csv').clean_names() mutation_df.head() ``` /home/jc604/.conda/envs/demeter2-stan/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3146: DtypeWarning: Columns (25,26,27,31) have mixed types.Specify dtype option on import or set low_memory=False. interactivity=interactivity, compiler=compiler, result=result) <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>hugo_symbol</th> <th>entrez_gene_id</th> <th>ncbi_build</th> <th>chromosome</th> <th>start_position</th> <th>end_position</th> <th>strand</th> <th>variant_classification</th> <th>variant_type</th> <th>reference_allele</th> <th>...</th> <th>iscosmichotspot</th> <th>cosmichscnt</th> <th>exac_af</th> <th>wes_ac</th> <th>sangerwes_ac</th> <th>sangerrecalibwes_ac</th> <th>rnaseq_ac</th> <th>hc_ac</th> <th>rd_ac</th> <th>wgs_ac</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>AGRN</td> <td>375790</td> <td>37</td> <td>1</td> <td>979072</td> <td>979072</td> <td>+</td> <td>Silent</td> <td>SNP</td> <td>A</td> <td>...</td> <td>False</td> <td>0</td> <td>NaN</td> <td>27:24</td> <td>9:10</td> <td>9:12</td> <td>104:20</td> <td>NaN</td> <td>NaN</td> <td>15:13</td> </tr> <tr> <th>1</th> <td>ATAD3A</td> <td>55210</td> <td>37</td> <td>1</td> <td>1459233</td> <td>1459233</td> <td>+</td> <td>Silent</td> <td>SNP</td> <td>A</td> <td>...</td> <td>False</td> <td>0</td> <td>0.000008</td> <td>29:49</td> <td>33:40</td> <td>30:38</td> <td>315:308</td> <td>NaN</td> <td>NaN</td> <td>17:31</td> </tr> <tr> <th>2</th> <td>NADK</td> <td>65220</td> <td>37</td> <td>1</td> <td>1685635</td> <td>1685635</td> <td>+</td> <td>Missense_Mutation</td> <td>SNP</td> <td>G</td> <td>...</td> <td>False</td> <td>0</td> <td>NaN</td> <td>25:39</td> <td>16:19</td> <td>17:20</td> <td>176:266</td> <td>NaN</td> <td>NaN</td> <td>14:23</td> </tr> <tr> <th>3</th> <td>PLCH2</td> <td>9651</td> <td>37</td> <td>1</td> <td>2436128</td> <td>2436128</td> <td>+</td> <td>Missense_Mutation</td> <td>SNP</td> <td>G</td> <td>...</td> <td>False</td> <td>0</td> <td>NaN</td> <td>9:20</td> <td>19:22</td> <td>20:20</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>23:15</td> </tr> <tr> <th>4</th> <td>LRRC47</td> <td>57470</td> <td>37</td> <td>1</td> <td>3703695</td> <td>3703695</td> <td>+</td> <td>Silent</td> <td>SNP</td> <td>G</td> <td>...</td> <td>False</td> <td>0</td> <td>0.000033</td> <td>19:21</td> <td>7:19</td> <td>8:17</td> <td>87:104</td> <td>NaN</td> <td>NaN</td> <td>11:16</td> </tr> </tbody> </table> <p>5 rows × 32 columns</p> </div> ```python mutation_columns = [ 'tumor_sample_barcode', 'hugo_symbol', 'chromosome', 'start_position', 'end_position', 'variant_classification', 'variant_type', 'protein_change' ] mutation_df = mutation_df[mutation_columns] ``` ```python hotspot_codons = [12, 13, 59, 61, 146] hotspot_codons_re = '12|13|59|61|146' kras_mutations = mutation_df \ .pipe(lambda x: x[x.hugo_symbol == 'KRAS']) \ .pipe(lambda x: x[x.variant_classification == 'Missense_Mutation']) \ .pipe(lambda x: x[x.protein_change.str.contains(hotspot_codons_re)]) \ [['tumor_sample_barcode', 'protein_change']] \ .drop_duplicates() \ .rename({'tumor_sample_barcode': 'cell_line'}, axis=1) \ .groupby('cell_line') \ .aggregate(lambda x: ';'.join(x.protein_change)) kras_mutations ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>protein_change</th> </tr> <tr> <th>cell_line</th> <th></th> </tr> </thead> <tbody> <tr> <th>A427_LUNG</th> <td>p.G12D</td> </tr> <tr> <th>A549_LUNG</th> <td>p.G12S</td> </tr> <tr> <th>AGS_STOMACH</th> <td>p.G12D</td> </tr> <tr> <th>AMO1_HAEMATOPOIETIC_AND_LYMPHOID_TISSUE</th> <td>p.A146T</td> </tr> <tr> <th>ASPC1_PANCREAS</th> <td>p.G12D</td> </tr> <tr> <th>...</th> <td>...</td> </tr> <tr> <th>SW948_LARGE_INTESTINE</th> <td>p.Q61L</td> </tr> <tr> <th>TCCPAN2_PANCREAS</th> <td>p.G12R</td> </tr> <tr> <th>TOV21G_OVARY</th> <td>p.G13C</td> </tr> <tr> <th>UMUC3_URINARY_TRACT</th> <td>p.G12C</td> </tr> <tr> <th>YD8_UPPER_AERODIGESTIVE_TRACT</th> <td>p.G138V</td> </tr> </tbody> </table> <p>114 rows × 1 columns</p> </div> ```python kras_mutations[kras_mutations.protein_change.str.contains(';')] ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>protein_change</th> </tr> <tr> <th>cell_line</th> <th></th> </tr> </thead> <tbody> <tr> <th>NCIH2291_LUNG</th> <td>p.G12V;p.G12C</td> </tr> </tbody> </table> </div> ```python mutation_df.to_csv(modeling_data_dir / 'ccle_mutations.csv', index=False) kras_mutations.to_csv(modeling_data_dir / 'kras_mutants.csv', index=True) ``` ```python ```
7c1bd066cce9a5d86ee55a491931e08ec4367926
[ "Markdown", "Python", "C++", "Shell" ]
10
Markdown
jhrcook/demeter2-stan
5d621322dbaf4c53ffb533e605106de15c847dc7
5cb66c301c51041df9e52116b8d90fce70e0dd3c
refs/heads/master
<file_sep>#!/usr/bin/env bash set -ex date input_file="$1" contract_name="$2" compiled_path="compiled/$(basename "$input_file")" solc --overwrite --bin-runtime "$input_file" -o "$compiled_path" docker run -v "$(pwd)":/tmp/host -it gigahorse "/tmp/host/docker-run-gigahorse" "/tmp/host/$compiled_path/$contract_name.bin-runtime" <file_sep>#!/usr/bin/env bash # NOTE: Will only get the first 1000 results, because that's what GitHub lets us access set -ex override="$1" data_dir="$2" if [[ -z "$data_dir" ]]; then data_dir="data" fi mkdir -p "$data_dir" for i in $(seq 1 10); do fname="$data_dir/data-$i.json" if [[ "$override" == "--override" ]] || [[ ! -e "$fname" ]]; then # NOTE: This search only finds repositories "Written in" (i.e., primarily in) Solidity curl "https://api.github.com/search/repositories?q=language:Solidity&sort=stars&order=desc&per_page=100&page=$i" > "$fname" # This search finds repositories containing Solidity code at all (based on extension and the word "contract", which every Solidity contract has to contain). At least, that's what it was supposed to do... # NOTE: This sort of search works on the GitHub website, but the API doesn't support using extension in a repository search. # curl "https://api.github.com/search/repositories?q=contract+extension:sol&sort=stars&order=desc&per_page=100&page=$i" > "$fname" fi done <file_sep>#!/usr/bin/env bash set -ex search_loc="$1" cur_list="$2" new_contracts="$(find "$search_loc" -name "*.sol" | grep -vFf "$cur_list" | shuf -n 5 | xargs -L1 basename)" echo "$new_contracts" echo "$new_contracts" >> "$cur_list" echo "$new_contracts" > new-contract-list <file_sep>#!/usr/bin/env bash set -e date git rev-parse HEAD cat "$1" | while read -r contract; do if [[ -f "smartbugs-wild/contracts/$contract" ]]; then loc="$(cloc --hide-rate --quiet --include-lang=Solidity --csv "smartbugs-wild/contracts/$contract" | grep "Solidity" | csvtool col 5 -)" echo "$loc" else # If it doesn't exist, 0 LOC to mark that there's no code echo "0" fi done <file_sep>#!/usr/bin/env bash set -ex date INFURA_ID="e375f839620843ca953814c877aa699c" time docker run --env "INFURA_ID=$INFURA_ID" mythril/myth "$@" # if [[ "$2" == "-a" ]]; then # docker run mythril/myth analyze "$@" # else # abs_path="$(realpath "$1")" # dir_path="$(dirname "$abs_path")" # fname="$(basename "$1")" # docker run -v "$dir_path":/tmp mythril/myth analyze /tmp/"$fname" # fi <file_sep>import sys from slither.slither import Slither def looks_like_state_check(contract, node): for v in contract.variables: if v in node.variables_read: return True return False def main(args): if len(args) < 2: print("Usage: python get-conditions.py FILENAME") exit(1) slither = Slither(args[1]) for contract in slither.contracts: # print('Contract: '+ contract.name) for function in contract.functions: # print('Function: {}'.format(function.name)) for node in function.nodes: # NOTE: This will also give `return bool;` as a condition. I'm not sure that this really should count, so I used a different machnism to get this information. # if node.is_conditional(): # print(node) if node.contains_if() or node.contains_require_or_assert(): print(looks_like_state_check(contract, node), node) if __name__ == '__main__': main(sys.argv) <file_sep>#!/usr/bin/env bash set -ex date input_file="$1" contract_name="$2" compiled_path="$(realpath "compiled/$(basename "$input_file")")" solc --overwrite --bin-runtime "$input_file" -o "$compiled_path" cd vandal/ pipenv run bin/analyze.sh "$compiled_path/$contract_name.bin-runtime" datalog/demo_analyses.dl <file_sep>#!/usr/bin/env bash set -ex date to_analyze="$1" ../bin/generatefacts "$to_analyze" out ./decompiler_compiled --facts out ../../gigahorse-clients/source_decompiler.dl_compiled ../../gigahorse-clients/get_source.py ../../gigahorse-clients/madmax.dl_compiled cat decompiled.sol cat Vulnerability_OverflowLoopIterator.csv cat Vulnerability_UnboundedMassOp.csv cat Vulnerability_WalletGriefing.csv <file_sep>#!/usr/bin/env bash if [[ -z "$1" ]]; then echo "Usage: $0 DATA_DIR" echo "DATA_DIR - The directory containing json files from GitHub's repository search API." exit 1 fi set -e date git rev-parse HEAD data_dir="$1" find "$data_dir" -name "*.json" | sort -V | while read -r fname; do jq -r ".items[].html_url" "$fname" done <file_sep>#!/usr/bin/env bash # NOTE: Will only get the first 1000 results, because that's what GitHub lets us access set -ex override="$1" data_dir="$2" if [[ -z "$data_dir" ]]; then data_dir="code-data" fi mkdir -p "$data_dir" github_token="$(cat "./github-token")" if [[ -z "$github_token" ]]; then echo "No github token found in ./github-token" exit 1 fi for i in $(seq 1 10); do fname="$data_dir/data-$i.json" while true; do if [[ "$override" == "--override" ]] || [[ ! -e "$fname" ]]; then curl -D "headers" -H "Authorization: token $github_token" "https://api.github.com/search/code?q=hyperledger+language:YAML+NOT+marbles&per_page=100&page=$i" > "$fname" retry_after="$(grep -E "Retry-After: " "headers" | sed -E "s/.*Retry-After: ([0-9]+).*/\1/g")" if [[ -n "$retry_after" ]]; then echo "[INFO] Got Retry-After: $retry_after. Sleeping for $retry_after seconds." sleep "$retry_after" continue else break fi else break fi done done
1b216752f5fb6cb415c0aed7c795971726921635
[ "Python", "Shell" ]
10
Shell
xueshijun/EVMCorpusStudy
23ad3b1004a90a300152071e9ae59424209c6575
5dedba5ccf53980eaab436165c571f8bae1208d1
refs/heads/master
<repo_name>laandrad/Text-Mining<file_sep>/myTMtools.py from types import StringType import io import nltk import os def get_imlist(path): # This function extracts a path toward each txt file inside 'path' folder return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.txt')] def category_tokens(path, name, method, bigrams): # This function does two things: # 1. read a text document from 'path' and convert words into token format # 2. Use 'name' argument to label to the extracted tokens with io.open(path, 'r', encoding='windows-1252') as doc: raw = doc.read() tokens = prepare_text(str(raw), method, bigrams) category = [] for i in range(len(tokens)): category.append(name) return zip(category, tokens) def prepare_text(raw_text, method=1, bigrams=0): # type: (raw_text, method, bigrams) -> features # This function does four things to retrieve only names and nouns in 'raw_text': # 1. retrieve a list of words from a 'raw_text' file # 2. tokenize words in list using NLTK # 3. create part-of-speech (POS) tags per token # 4. stem tokens using the Porter stemmer filter # 5. method 1 uses nouns only, method 2 uses nouns and adverbs # 6. Bigrams, boolean variable, that would additionally include bigrams """ :rtype: features """ assert isinstance(raw_text, StringType), "text is not a string: %r" % raw_text raw = raw_text porter = nltk.PorterStemmer() nouns = ['NN', 'NNP', 'NNS'] advs = ['JJ', 'VBN'] if method == '1': pos_tags = nouns else: pos_tags = nouns + advs sentences = raw.split('.') document = [] for s in sentences: tokens = nltk.word_tokenize(s) words = [w.lower() for w in tokens if w.isalpha()] # print 'creating POS tags' tags = nltk.pos_tag(words) names = [w.lower() for w, t in tags if t in pos_tags] names = [porter.stem(t) for t in names] if bigrams == '1': relations = list(nltk.bigrams(names)) else: relations = [] document = document + names + relations return document <file_sep>/main.py import os import pandas as pd from sys import argv from scipy import spatial from tools import * from numpy import isnan from io import open def main(): """this is the run file""" test_folders = argv[1] benchmark_file = argv[2] output_path = argv[3] method = ['n', 'a', 'a'] bigram = ['False', 'False', 'True'] output_file = output_path + '/' + 'method_comparison_cosine_values.csv' with open(test_folders, 'r') as f: test_folders = f.read() test_folders = test_folders.splitlines() with open(benchmark_file, 'r') as f: benchmark_file = f.read() benchmark_file = benchmark_file.splitlines() # initialize big data frame frames = [] for k in xrange(len(benchmark_file)): test = str(test_folders[k]).replace('"', '') print "Reading test files from folder:" print test benchmark = str(benchmark_file[k]).replace('"', '') print "Reading benchmark form file:" print benchmark # read file paths from test documents folder query = sorted([os.path.join(test, f) for f in os.listdir(test) if f.endswith('.txt')]) # load benchmark text file with open(benchmark, "r", encoding="utf-8", errors='ignore') as doc: raw = doc.read() # initialize dict of dicts for data frame method_csv = {} for j in xrange(len(method)): # extract features from benchmark dtm = ExtractFeatures(method[j], bigram[j]) benchmark_name = benchmark_file[k].split('\\')[-1] benchmark_features = dtm.extract_features_from_text(raw, benchmark_name) # extract terms from each text document to create a vocabulary (keeping unique terms only) vocabulary = sorted(set(w[1] for w in benchmark_features)) print "{0} features produced.".format(str(len(vocabulary))) benchmark_dtv = DTM(vocabulary, benchmark_name, benchmark_features) benchmark_dtv = benchmark_dtv.compute_dtv() # load test document features test_features = [] for q in query: dtm1 = ExtractFeatures(method[j], bigram[j]) test_features = test_features + dtm1.extract_features_from_file(q) documents = sorted(set([d for d, w in test_features])) print "{0} test documents read.".format(str(len(documents))) print "Computing DTM..." test_dtm = DTM(vocabulary, documents, test_features) test_dtm = test_dtm.compute_dtm() print "Computing cosine values..." dv = {} for i in xrange(len(documents)): d = 1 - spatial.distance.cosine(benchmark_dtv[benchmark_name], test_dtm[documents[i]]) if isnan(d): d = 0 dv[documents[i]] = d this_method = "method=" + method[j] + '_' + "bigram=" + bigram[j] method_csv[this_method] = pd.Series(dv) print "Saving to data frame..." df = pd.DataFrame(method_csv) test = test.split('\\')[-1] test = test.split('.')[0] df['test_group'] = test frames.append(df) result = pd.concat(frames) print "Saving results to file: ", output_file result.to_csv(output_file) print 'Finished computing {0} data frames'.format(str(len(test_folders))) if __name__ == '__main__': main() <file_sep>/README.md # Text-Mining Project ## A Latent Semantic Analysis (LSA) to measure 'disciplinary discourse' similaries between text documents This GitHub repository includes the files used in the project entitled: "Exploring a Text-Mining Approach as Rapid Prototyping Tool for Formative-Assessment Development in Problem-Based Learning Environments" # How to Use extractDTM_computeCosineValues.py ## Note: requires NLTK, NUMPY, and SCIPY packages ## Note: extractDTM_computeCosineValues.py has been written in Python 2.7, it might not run in Python 3 versions ### Command prompt python extractDTM_computeCosineValues.py 'input_path' 'output_path' 'title' 'method' 'bigrams' ### Argument definition 'input_path' is a folder path with text documents (i.e., '.txt' files) 'output_path' is a folder path where csv files will be written with output matrices 'title' is a string with a label/identifier for the text documents (e.g., 'pre' or 'post') 'method' defines what terms should be included in the vector space representation. 'method' = 1 would include nouns only; 'method' = 2 would include nouns and adverbs 'bigrams' defines whether bigrams should be included in the vector space representation. 'bigrams' = True would compute all the bigrams in each vector computed with method 'method'. 'bigrams' = False would not compute bigrams. ### Output extractDTM_computeCosineValues.py retrieves two matrices: (1) a document-term matrix of norm i,j where rows (i) are documents and columns (j) are terms, and (2) a pairwise cosine similarity values matrix of norm k (a symmetric matrix), where k is the number of text documents # How to Use tm2.py ## Note: requires NLTK and NUMPY packages ## Note: tm2.py has been written in Python 2.7, it might not run in Python 3 versions. For Python 3 use tm2_3.py ### Command prompt python tm2.py 'input_folder' 'output_folder' ### Argument definition 'input_folder' is the folder path to the three folders called "pre", "during", and "post" 'output_folder' is the folder path where you want to save the csv files with the dtm matrices per each folder (i.e., pre, during, post) ### Output tm2.py retrieves three document-term matrices for text documents inside "pre", "during", and "post" folders <file_sep>/sliding_window.py import nltk, sys, json from itertools import tee, izip def slice_document(transcript_file, output_folder): with open(transcript_file, 'r') as file: raw = file.read() raw = raw.replace('\x92', "'") tokens = nltk.word_tokenize(raw) words = [w.lower() for w in tokens if w.isalnum()] print 'Number of tokens: ', len(tokens) print 'Number of words: ', len(words) i = 1 path = output_folder + '/' for each in window(words, 100): print list(each) with open(path + 'window' + str(i) + '.txt', 'w') as f: json.dump(each, f) i += 1 def window(iterable, size): iters = tee(iterable, size) for i in xrange(1, size): for each in iters[i:]: next(each, None) return izip(*iters) def main(): transcript_file = sys.argv[1] output_folder = sys.argv[2] slice_document(transcript_file, output_folder) if __name__ == '__main__': main() <file_sep>/p34_extractDTM_computeCosineValues.py import nltk, os, numpy as np, csv, sys from scipy import spatial def get_dtm(input_path, output_path, title): ### This algorithm does two things: ### 1. It computes a document-term matrix for the text documents inside 'input_path' folder ### 2. It computes all pairwise cosine similarity values between the text documents # get a path to the text files in 'input_path' folder query = sorted(get_imlist(input_path)) # extract subject name for each text document subject = [query[i][-13:-4] for i in range(len(query))] # read the text documents and convert words into tokens, # then bind all (tokens, subject) pairs into a list terms_by_subject = [] for i in range(len(subject)): terms = category_tokens(query[i], subject[i]) terms_by_subject = terms_by_subject + terms # create a frequency distribution from the (tokens, subject) list cfd = nltk.ConditionalFreqDist(terms_by_subject) # extract terms from each text document to create a vocabulary (keeping unique terms only) vocabulary = sorted(set(w[1] for w in terms_by_subject)) print(vocabulary) # initilize dtm file writer and write the header with the vocabulary # a 'title_dtm.csv' file will be written inside 'output_path' folder dtm_file = output_path + '/' + str(title) + '_dtm.csv' with open(dtm_file, 'w') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(vocabulary) # create a document-term matrix and write into csv file initialized above # 1. extract term frequencies from each text document - a.k.a. frequency vectors # 2. bind all frequency vectors into a dtm matrix dtm = [] for ss in subject: dtv = [cfd[ss][word] for word in vocabulary] # vector of frequencies per vocabulary term print('Computing term-frequency vector for: ', ss) with open(dtm_file, 'a') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(dtv) dtm.append(dtv) # initialize cosine similarity matrix file writer and write the header with the subject names # a 'title_cosine.csv' file will be written inside 'output_path' folder csm_file = output_path + '/' + str(title) + '_cosine.csv' with open(csm_file, 'w') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(subject) # compute a pairwise cosine values between (i, j) frequency vectors # bind all values into a matrix and write into csv file initialize above for i in range(len(dtm)): dv = [] for j in range(len(dtm)): d = 1 - spatial.distance.cosine(dtm[j], dtm[i]) print(i, j, d) dv.append(d) with open(csm_file, 'a') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(dv) def get_imlist(path): ### This function extracts a path toward each txt file inside 'path' folder return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.txt')] def category_tokens(path, name): ### This function does two things: ### 1. read a text document from 'path' and convert words into token format ### 2. Use 'name' argument to label to the extracted tokens with open(path, 'r') as file: raw = file.read() tokens = prepare_text(raw) category = [] for i in range(len(tokens)): category.append(name) return list(zip(category, tokens)) def prepare_text(raw_text): ### This function does four things to retrieve only names and nouns in 'raw_text': ### 1. retrieve a list of words from a 'raw_text' file ### 2. tokenize words in list using NLTK ### 3. create part-of-speech (POS) tags per token ### 4. stem tokens using the Porter stemmer filter raw = raw_text raw = raw.replace('\x92', "'") tokens = nltk.word_tokenize(raw) words = [w.lower() for w in tokens if w.isalpha()] tags = nltk.pos_tag(words) # normalize to lower and use POS tags to get only names and nouns in 'nouns' nouns = ['NN', 'NNP', 'NNS'] # stop_words_tags = ['DT', 'PRP', 'IN', '.', ',', '(', ')', 'TO', 'RB'] # a stopword filter might be required names = [w.lower() for w,t in tags if t in nouns] porter = nltk.PorterStemmer() names = [porter.stem(t) for t in names] return names def main(): input_path = sys.argv[1] output_path = sys.argv[2] title = sys.argv[3] get_dtm(input_path, output_path, title) if __name__ == '__main__': main() <file_sep>/transcript.py # import os from io import open from sys import argv import pandas as pd from numpy import isnan from scipy import spatial from tools import * def main(): """this is the run file""" transcript_files = argv[1] benchmark_files = argv[2] output_path = argv[3] method = 'a' bigram = 'False' output_file = output_path + '/' + 'transcripts_cosine_values.csv' # load file which points to transcript files with open(transcript_files, 'r', encoding="utf-8", errors='ignore') as f: transcript_files = f.read() transcript_files = transcript_files.splitlines() with open(benchmark_files, 'r', encoding="utf-8", errors='ignore') as f: benchmark_files = f.read() benchmark_files = benchmark_files.splitlines() # load k transcript and benchmark files frames = [] for k in range(len(transcript_files)): benchmark_file = str(benchmark_files[k]).replace('"', '') print benchmark_file with open(benchmark_file, 'r', encoding="utf-8", errors='ignore') as f: benchmark = f.read() transcript_file = str(transcript_files[k]).replace('"', '') print "Reading text from file: ", transcript_file group = transcript_file.split("\\") group = group[-1].split(".")[0] with open(transcript_file, 'r', encoding="utf-8", errors='ignore') as f: transcript = f.read() transcript = transcript.splitlines() # load expert vocabulary and features bench_features = ExtractFeatures(method, bigram) bench_features = bench_features.extract_features_from_text(benchmark, 'benchmark') vocabulary = sorted(set(w[1] for w in bench_features)) # iterate over each line dict_dv = {} dict_n = {} dict_g = {} i = 1 for line in transcript: # print line text = nltk.word_tokenize(line) time, name, line = [text[1], text[3], text[4:]] assert time[0] == "0" and time[2] == ":",\ "Time slot not a time before: " + text[0] + ' ' + text[1] + ' ' + group # print time[2] + name + group line = ' '.join(line) line_features = ExtractFeatures(method, bigram) line_features = line_features.extract_features_from_text(line, name) features = line_features + bench_features dtm = DTM(vocabulary, [name, 'benchmark'], features) dtm = dtm.compute_dtm() print "Computing cosine values for line", i, "of", len(transcript), "in transcript", k, "of", len(transcript_files) if not sum(dtm[name]) == 0: d = 1 - spatial.distance.cosine(dtm[name], dtm['benchmark']) else: d = 0 if isnan(d): d = 0 dict_dv[time] = d dict_n[time] = name dict_g[time] = group i += 1 df = {'dv': pd.Series(dict_dv), 'ID': pd.Series(dict_n), 'Group': pd.Series(dict_g)} df = pd.DataFrame(df) frames.append(df) result = pd.concat(frames) print result print "Saving results to file: ", output_file result.to_csv(output_file) print 'Finished computing {0} data frames'.format(str(len(transcript_files))) if __name__ == '__main__': main() <file_sep>/p34_tm2.py import nltk, os, numpy as np, csv, sys def get_dtm(path, path_out): query = sorted(get_imlist(path)) # the text files in folder subject = [query[i][-13:-4] for i in range(len(query))] # extract the subject name # read the files and convert words into tokens terms_by_subject = [] for i in range(len(subject)): ##for i in range(2): terms = category_tokens(query[i], subject[i]) terms_by_subject = terms_by_subject + terms # create a frequency distribution cfd = nltk.ConditionalFreqDist(terms_by_subject) # extract the terms/vocabulary across text files vocabulary = sorted(set(w[1] for w in terms_by_subject)) print(vocabulary) # initilize file writing dtm_file = path_out + path[-4:-1] + '.csv' print(dtm_file) with open(dtm_file, 'w') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(vocabulary) # extract the frequencies to create a document-term matrix and write a csv file with the dtm dtm = [] for ss in subject: dtv = [cfd[ss][word] for word in vocabulary] # vector of frequencies per vocabulary term print(ss) print(dtv) with open(dtm_file, 'a') as csvfile: writer = csv.writer(csvfile, delimiter = ',') writer.writerow(dtv) def get_imlist(path): # a function to extract all the txt files in a given folder return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.txt')] def category_tokens(path, name): # a function to zip the words to a student label file = open(path, 'r') raw = file.read() tokens = prepare_text(raw) category = [] for i in range(len(tokens)): category.append(name) return list(zip(category, tokens)) def prepare_text(raw_text): # a function to retrieve a list of words after applying a given POS and stemmer filters raw = raw_text raw = raw.replace('\x92', "'") tokens = nltk.word_tokenize(raw) tags = nltk.pos_tag(tokens) nouns = ['NN', 'NNP', 'NNS'] ##stop_words_tags = ['DT', 'PRP', 'IN', '.', ',', '(', ')', 'TO', 'RB'] names = [w.lower() for w,t in tags if t in nouns] # normalize to lower and get only names and nouns porter = nltk.PorterStemmer() names = [porter.stem(t) for t in names] return names def main(): path = sys.argv[1] path_out = sys.argv[2] path_pre = path + "/pre/" pre = get_dtm(path_pre, path_out) path_dur = path + "/during/" during = get_dtm(path_dur, path_out) path_post = path + "/post/" post = get_dtm(path_post, path_out) if __name__ == '__main__': main()
45baff035ebff6a8b0b2b84daac0bf8a2d265541
[ "Markdown", "Python" ]
7
Python
laandrad/Text-Mining
bf1293845bf1bf823a928aa466d3be95bc1f43d9
6238fbd81a6109fafd991e9cecaea0aed8a4392d
refs/heads/master
<repo_name>fomindanny/Mandelbrot-Set<file_sep>/mandelbrot_set.py import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def iterations_until_diverge(complex_number: complex, threshold: int) -> int: """Returns an amount of iterations until function diverges. Function is z(n + 1) = z ^ 2 + c. Function diverges when |z| > 4. """ z = complex(0, 0) for iteration in range(threshold): z = z**2 + complex_number if abs(z) > 4: break return iteration def mandelbrot_set(threshold: int, density: int): """Mandelbrot Set realisation. Saves an image to the program directory. """ real_axis = np.linspace(-2, 1, density) imaginary_axis = np.linspace(-1.5, 1.5, density) matrix = np.empty((density, density)) for row in range(density): for col in range(density): complex_number = complex(real_axis[row], imaginary_axis[col]) matrix[row, col] = iterations_until_diverge(complex_number, threshold) file_name = "mandelbrot_set.png" plt.imsave(file_name, matrix.T, cmap="magma") def mandelbrot_set_animation(density: int): """Mandelbrot Set animation. Saves an animation to the program directory. """ real_axis = np.linspace(-2, 1, density) imaginary_axis = np.linspace(-1.5, 1.5, density) fig = plt.figure() fig.set_size_inches(10, 10) axes = plt.Axes(fig, [0, 0, 1, 1]) fig.add_axes(axes) def animate(i): matrix = np.empty((density, density)) threshold = i + 1 for row in range(density): for col in range(density): complex_number = complex(real_axis[row], imaginary_axis[col]) matrix[row, col] = iterations_until_diverge(complex_number, threshold) image = axes.imshow(matrix.T, interpolation="bicubic", cmap="magma") return [image] figure_animation = animation.FuncAnimation(fig, animate, frames=120, interval=40, blit=True) file_name = "mandelbrot_set.gif" figure_animation.save(file_name, writer="imagemagick") <file_sep>/README.md # Mandelbrot Set Mandelbrot Set visualization
593b4bee32a0041f441a9b8b899f7644c51db35d
[ "Markdown", "Python" ]
2
Python
fomindanny/Mandelbrot-Set
30771387972c92e580669359c55715e904c55596
9ee26dd19de694a895875ff13edf7ce584ad3fa2
refs/heads/master
<repo_name>ccwei/textSupport<file_sep>/ModRest.rb require 'rest-client' DOMAINNAME = 'text-support.org' ADMIN_ACCOUNT = 'admin' ADMIN_PASSWORD = '<PASSWORD>' def send_ctl_command(command) server_str = 'http://' + DOMAINNAME + ':5285/rest/' auth_str = '--auth ' + ADMIN_ACCOUNT + ' ' + DOMAINNAME + ' ' + ADMIN_PASSWORD + ' ' print server_str + '\n' print auth_str + '\n' response = RestClient.post(server_str, auth_str + command) end <file_sep>/app/models/member.rb class Member < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :nickname, :gender,\ :occupation, :description, :device_token, :enable_notdisturb scope :listeners, where(:is_listener => true) def jid id.to_s end def start_at split = self.notdisturb.('-', 2) split.first end def start_at=(start_at) end end <file_sep>/db/migrate/20130624215434_add_enable_not_disturb_to_member.rb class AddEnableNotDisturbToMember < ActiveRecord::Migration def change add_column :members, :enable_notdisturb, :string end end <file_sep>/app/models/spool.rb class Spool < ActiveRecord::Base self.table_name = 'spool' self.primary_key = 'seq' scope :not_notified, where(:notified => false) def self.sendAPNs Spool.not_notified.group_by(&:username).each do |userid, msgs| m = Member.find(userid) APNS.pem = "#{Rails.root}/lib/tasks/APNCert.pem" if m.device_token.present? APNS.send_notification(m.device_token, :alert => 'New Message Received!', :badge => msgs.count, :sound => 'default') end msgs.each do |m| m.notified = true m.save end puts userid + ":" + msgs.count.to_s end end end <file_sep>/test/unit/helpers/beta_emails_helper_test.rb require 'test_helper' class BetaEmailsHelperTest < ActionView::TestCase end <file_sep>/app/controllers/registrations_controller.rb require './ModRest.rb' class RegistrationsController < Devise::RegistrationsController def register_XMPP_user(username, password) logger.info 'create user:' + username register_str = 'register ' + username + ' ' + DOMAINNAME + ' ' + password response = send_ctl_command(register_str) end #GET /resource/edit def edit @notdisturb = resource.notdisturb @notdisturb = @notdisturb.split(" ") logger.debug @notdisturb.inspect render :template => 'members/registrations/edit' end def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) logger.debug self.resource.inspect prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email) logger.debug "============params = " + params.inspect if resource.update_with_password(resource_params) resource.notdisturb = params["notdisturb_from"] + " " + params["from_ampm"] + " " + params["notdisturb_to"] + " " + params["to_ampm"] resource.save if is_navigational_format? flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? :update_needs_confirmation : :updated set_flash_message :notice, flash_key end sign_in resource_name, resource, :bypass => true respond_with resource, :location => after_update_path_for(resource) else clean_up_passwords resource respond_with resource end end def update_device_token if params[:email].present? and params[:device_token].present? member = Member.find_by_email(params[:email]) member.device_token = params[:device_token] member.save end end def create logger.info '=================create===============' params[:member][:email] = params[:member][:email].strip if params[:member] and params[:member][:email] build_resource email = params[:member][:email] if resource.save if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_navigational_format? sign_up(resource_name, resource) member = Member.find_by_email(email) if member.present? xmpp_username = member.id.to_s xmpp_password = params[:member][:password] end register_XMPP_user(xmpp_username, xmpp_password) respond_with resource do |format| format.json {render :json => resource} format.html {redirect_to after_sign_up_path_for(resource)} end else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format? expire_session_data_after_sign_in! respond_with resource do |format| format.json {render :json => resource} format.html {redirect_to after_inactive_sign_up_path_for(resource)} end end else clean_up_passwords resource respond_with resource do |format| format.json {render :json => resource} format.html {redirect_to root_url} end end end end <file_sep>/app/controllers/pages_controller.rb class PagesController < ActionController::Base before_filter :authenticate_user!, :only => [:login] #ssl_required :login # you have to set up ssl and ssl_requirement def login @user = current_user respond_to do |format| format.html {render :text => "#{@user.id}"} #format.xml {render :text => "#{@user.id}" } format.json {render :json => "#{@user.id}"} end end def about render 'about', :layout => 'application' end def info render 'info', :layout => 'application' end def privacy render 'privacy', :layout => 'application' end def terms render 'terms', :layout => 'application' end def contacts render 'contacts', :layout => 'application' end def user_list @member = Member.where("created_at > :date", date: "2013-05-18 00:00:00") @users = BetaEmail.where("created_at > :date", date: "2013-05-18 00:00:00") render 'user_list', :layout => 'application' end def one_minute render 'one_minute', :layout => 'application' end end <file_sep>/app/controllers/sessions_controller.rb class SessionsController < Devise::SessionsController def new super end def create #logger.info 'accept' + request.inspect logger.info '------' resource = warden.authenticate!(auth_options) logger.info resource.inspect set_flash_message(:notice, :signed_in) sign_in(resource_name, resource) respond_with(resource) do |format| format.json {render :json => resource} format.html {redirect_to root_url} end end def auth_options { :scope => resource_name, :recall => "#{controller_path}#new" } end end <file_sep>/test/functional/beta_emails_controller_test.rb require 'test_helper' class BetaEmailsControllerTest < ActionController::TestCase setup do @beta_email = beta_emails(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:beta_emails) end test "should get new" do get :new assert_response :success end test "should create beta_email" do assert_difference('BetaEmail.count') do post :create, beta_email: @beta_email.attributes end assert_redirected_to beta_email_path(assigns(:beta_email)) end test "should show beta_email" do get :show, id: @beta_email assert_response :success end test "should get edit" do get :edit, id: @beta_email assert_response :success end test "should update beta_email" do put :update, id: @beta_email, beta_email: @beta_email.attributes assert_redirected_to beta_email_path(assigns(:beta_email)) end test "should destroy beta_email" do assert_difference('BetaEmail.count', -1) do delete :destroy, id: @beta_email end assert_redirected_to beta_emails_path end end <file_sep>/app/controllers/mains_controller.rb class MainsController < ActionController::Base def main render 'main', :layout => 'application' end end <file_sep>/app/controllers/chatusers_controller.rb require './ModRest.rb' class ChatusersController < ActionController::Base def random_user offset = rand(Member.listeners.count) #rand_member = Member.find(43) rand_member = Member.listeners.first(:offset => offset) #render :json => rand_member.jid.to_json() return rand_member end #user1 is jid, user2 is Member def add_rosteritem user1, user2 add_rosteritem_str = 'add_rosteritem ' + user1 + ' ' + DOMAINNAME + ' ' + user2.jid + ' ' + DOMAINNAME + ' ' + user2.nickname + ' Buddies both' response = send_ctl_command(add_rosteritem_str) end def chat_random_user user1 = params[:user] if user1 == "42" user2 = Member.find(300) else user2 = random_user end add_rosteritem user1, user2 listenerJID = user2.jid + '@' + DOMAINNAME user1JID = user1 + '@' + DOMAINNAME #send_default_msg listenerJID, user1JID render :json => {:listenerJid => listenerJID, :nickname => user2.nickname, :desc => user2.description, :gender => user2.gender}.to_json() end def get_nick_name jid = params[:jid] id = jid[0...jid.index('@')].to_i logger.info id.to_s member = Member.find_by_id(id) if member.is_listener render :json => {:nickname => member.nickname}.to_json() else render :json => {:nickname => 'User #' + id.to_s}.to_json() end end def send_default_msg from, to body = "\"Hi! Is there something you would like to talk about today?\"" send_message_chat = 'send_message_chat ' + from + ' '+ to + ' ' + body logger.info send_message_chat response = send_ctl_command(send_message_chat) end end <file_sep>/app/controllers/beta_emails_controller.rb class BetaEmailsController < ApplicationController # GET /beta_emails # GET /beta_emails.json def index @beta_emails = BetaEmail.all respond_to do |format| format.html # index.html.erb format.json { render json: @beta_emails } end end # GET /beta_emails/1 # GET /beta_emails/1.json def show @beta_email = BetaEmail.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @beta_email } end end # GET /beta_emails/new # GET /beta_emails/new.json def new @beta_email = BetaEmail.new respond_to do |format| format.html # new.html.erb format.json { render json: @beta_email } end end # GET /beta_emails/1/edit def edit @beta_email = BetaEmail.find(params[:id]) end # POST /beta_emails # POST /beta_emails.json def create @beta_email = BetaEmail.new(params[:beta_email]) if @beta_email.save render 'create', :layout => false end end # PUT /beta_emails/1 # PUT /beta_emails/1.json def update @beta_email = BetaEmail.find(params[:id]) respond_to do |format| if @beta_email.update_attributes(params[:beta_email]) format.html { redirect_to @beta_email, notice: 'Beta email was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @beta_email.errors, status: :unprocessable_entity } end end end # DELETE /beta_emails/1 # DELETE /beta_emails/1.json def destroy @beta_email = BetaEmail.find(params[:id]) @beta_email.destroy respond_to do |format| format.html { redirect_to beta_emails_url } format.json { head :no_content } end end end <file_sep>/db/migrate/20130414204222_add_info_to_member.rb class AddInfoToMember < ActiveRecord::Migration def change add_column :members, :gender, :string add_column :members, :occupation, :string add_column :members, :description, :string end end <file_sep>/lib/tasks/sendAPNs.rake namespace :TS do task :send_apns => :environment do Spool.sendAPNs end task :sleep_send_apns => :environment do sleep(30) Spool.sendAPNs end end <file_sep>/db/migrate/20130408172837_add_listener_to_member.rb class AddListenerToMember < ActiveRecord::Migration def change add_column :members, :is_listener, :boolean, :default => 0 end end
56b8ef0d527f531b285a07d5715d7bca8c60f294
[ "Ruby" ]
15
Ruby
ccwei/textSupport
6aa86496082049eb483d17149ea1596da8497f75
2645db61a2ac8c5e46aa54708cad3471cbfd17fd
refs/heads/master
<file_sep>package fr.r0x.main; import java.sql.*; import java.util.Date; import java.text.SimpleDateFormat; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; public class MySQLManager { private Main plugin; private Connection con; private String url; private String user; private String mdp; private String table; private String message; private String format; public boolean erreur; public MySQLManager(Main plg) { plugin = plg; url = plugin.conf.getUrl(); user = plugin.conf.getUser(); mdp = plugin.conf.getMdp(); table = plugin.conf.getTable(); message = "Grâce à votre achat, vous avez reçu : "; format = "dd/MM/yyyy - HH:mm:ss"; erreur = false; } public void connection() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, mdp); } catch (Exception e) { plugin.getServer().getConsoleSender().sendMessage(plugin.getName() + " : Erreur lors de la connection -> " + e); erreur = true; } } public void deconnection() { try { con.close(); } catch (SQLException e) { plugin.getServer().getConsoleSender().sendMessage(plugin.getName() + " : Erreur lors de la deconnection -> " + e); } } public void sendItem(String name) { try { Statement stat = con.createStatement(); ResultSet res = stat.executeQuery("SELECT * FROM " + table); while(res.next()) { if(res.getString("nom").equals(name) && res.getString("reception_faite").equals("non")) { int id = Integer.parseInt(res.getString("id_block")); ItemStack item = new ItemStack(id); item.setAmount(Integer.parseInt(res.getString("nombre"))); plugin.getServer().getPlayer(name).getInventory().addItem(item); plugin.getServer().getPlayer(name).sendMessage(message + res.getInt("nombre") + " " + Material.getMaterial(id) + " à la date : " + dateReception()); } } res.close(); stat.executeUpdate("UPDATE " + table + " SET date_reception = '" + dateReception() + "' WHERE nom LIKE '" + name + "' AND reception_faite LIKE 'non'"); stat.executeUpdate("UPDATE " + table + " SET reception_faite = 'oui' WHERE nom LIKE '" + name + "'"); stat.close(); } catch (SQLException e) { plugin.getServer().getConsoleSender().sendMessage(plugin.getName() + " : Erreur lors de la gestion de la base de donnee -> " + e); erreur = true; } } public String dateReception() { return new SimpleDateFormat(format).format(new Date()); } } <file_sep>package fr.r0x.main; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class EventManager implements Listener{ private Main plugin; public EventManager(Main plg) { plugin = plg; } @EventHandler(priority = EventPriority.HIGH) public void ConnectedPlayer(PlayerJoinEvent event) { if(!plugin.sql.erreur) { plugin.sql.sendItem(event.getPlayer().getName()); } } } <file_sep>package fr.r0x.main; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin { public MySQLManager sql; public ConfigManager conf; @Override public void onEnable() { this.getConfig().options().copyDefaults(true); this.saveConfig(); conf = new ConfigManager(this); sql = new MySQLManager(this); sql.connection(); PluginManager manager = this.getServer().getPluginManager(); manager.registerEvents(new EventManager(this), this); } @Override public void onDisable() { if(!sql.erreur) { sql.deconnection(); } } }
34b4c29b05266cba907c6e73e2de89a6f8df1271
[ "Java" ]
3
Java
Cilag/r0xShop
4780e39ec9ce7916f7c3cbb2e137faab9cc9c1cc
904815c92a0f552858ef59f542a0b2c98db5d61f
refs/heads/main
<repo_name>nuhu-ibrahim/Python-Twitter-V2-API-examples<file_sep>/README.md # Python-Twitter-V2-API-examples Python codes for using Twitter v2 for username lookup and full archive search. Note that the full archive search requires access via the Academic Researcher Twitter product track. <file_sep>/read_historical_twitter.py # imports import requests import os import json import time import pymongo import datetime import numpy as np from pymongo import MongoClient from datetime import datetime, timezone, timedelta # returns the bearer token def auth(): # TODO add bearer token of developer Twitter for academic research (!important) bearer_token = "" return bearer_token # creates and returns the request header def create_headers(bearer_token): """ Parameters ---------- bearer_token : str Twitter bearer token """ headers = {"Authorization": "Bearer {}".format(bearer_token)} return headers # creates a url for looking up a twitter username def create_lookup_url(usernames, user_fields): """ Parameters ---------- usernames : str Username that you want to search. => Sample: usernames=TwitterDev <= user_fields : str User fields are adjustable, options include: created_at, description, entities, id, location, name, pinned_tweet_id, profile_image_url, protected, public_metrics, url, username, verified, and withheld => Sample: user.fields=description,created_at <= """ url = "https://api.twitter.com/2/users/by?{}&{}".format( usernames, user_fields) return url # sends a request to the username lookup url and catch the exception if any happens def connect_to_lookup_endpoint(url, headers): response = requests.request("GET", url, headers=headers) # print(response.status_code) if response.status_code != 200: raise Exception( "Request returned an error: {} {}".format( response.status_code, response.text ) ) return response.json() # lookup a username on twitter with some specific fields and return a response def lookup_user(username, user_fields=""): """ Parameters ---------- username : str Username that you want to search. => Sample: usernames=TwitterDev <= user_fields : str User fields are adjustable, options include: created_at, description, entities, id, location, name, pinned_tweet_id, profile_image_url, protected, public_metrics, url, username, verified, and withheld => Sample: user.fields=description,created_at <= """ bearer_token = auth() url = create_lookup_url(username, user_fields) headers = create_headers(bearer_token) json_response = connect_to_lookup_endpoint(url, headers) return json_response # returns true if a twitter username exists and false otherwise def confirm_username(username): """ Parameters ---------- usernames : str Username that you want to search. => TwitterDev <= """ username_attr = "usernames="+username user_response = lookup_user(username_attr) if 'data' in user_response and len(user_response['data']) > 0 and 'username' in user_response['data'][0] and username.lower() == user_response['data'][0]['username'].lower(): return True return False # returns the twitter full archive url def full_archive_url(): search_url = "https://api.twitter.com/2/tweets/search/all" return search_url # connects to the full archive url and return a response or throw an exception def connect_to_search_endpoint(url, headers, params): search_url = full_archive_url() response = requests.request( "GET", search_url, headers=headers, params=params) # print(response.status_code) if response.status_code != 200: raise Exception(response.status_code, response.text) return response.json() # searches for a query on twitter and return the response def keyword_spartial_search(query, start_date_request, end_date_request, next_token=0, tweets_per_request=100): search_url = full_archive_url() query_params = { 'query': query, 'max_results': tweets_per_request, 'start_time': start_date_request, 'end_time': end_date_request, 'tweet.fields': 'attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld', 'expansions': 'attachments.poll_ids,attachments.media_keys,author_id,entities.mentions.username,geo.place_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id', 'user.fields': 'id,username,location,created_at,description', 'place.fields': 'contained_within,country,country_code,full_name,geo,id,name,place_type', 'media.fields': 'duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics' } if next_token != 0: query_params['next_token'] = next_token bearer_token = auth() headers = create_headers(bearer_token) json_response = connect_to_search_endpoint( search_url, headers, query_params) return json_response # extracts tweets from every response def extract_response_tweets(response): tweets = [] if 'data' in response and len(response['data']) != 0: tweets = response['data'] return tweets # extracts media from every response def extract_response_medias(response): media = [] if 'includes' in response and 'media' in response['includes'] and len(response['includes']['media']) != 0: media = response['includes']['media'] return media # extract users from every response def extract_response_users(response): users = [] if 'includes' in response and 'users' in response['includes'] and len(response['includes']['users']) != 0: users = response['includes']['users'] return users # extract places from every response def extract_response_places(response): places = [] if 'includes' in response and 'places' in response['includes'] and len(response['includes']['places']) != 0: places = response['includes']['places'] return places # extract tweet information from every response def extract_response_tweets_info(response): tweets_info = [] if 'includes' in response and 'tweets' in response['includes'] and len(response['includes']['tweets']) != 0: tweets_info = response['includes']['tweets'] return tweets_info # extract errors from every response def extract_response_errors(response): errors = [] if 'errors' in response and len(response['errors']) != 0: errors = response['errors'] return errors # extracts token from every response def extract_next_token(response): next_token = 0 if 'meta' in response and 'next_token' in response['meta']: next_token = response['meta']['next_token'] return next_token # checks whether the search should be continued def should_continue_search(tweets_count, number_of_tweets, next_token): continue_search = False if next_token != 0 and not (number_of_tweets != -1 and tweets_count > number_of_tweets): continue_search = True else: # Search should end if there is no next token or if expected tweets have been found continue_search = False return continue_search # performs a search based on set conditions, i.e., both date span and minimum number of tweets def retrieve_keyword_spartial(keyword_query, spatial_query, start_date, end_date, number_of_tweets=-1): is_first = True continue_search = False search_response = None next_token_ = 0 query = ' '.join([keyword_query, spatial_query]) tweets = [] users = [] places = [] tweet_infos = [] errors = [] media = [] start_date_obj = datetime.strptime(start_date, '%Y-%m-%d') start_date_request = str(start_date_obj.replace( tzinfo=timezone.utc)).replace(" ", "T") end_date_obj = datetime.strptime(end_date, '%Y-%m-%d') end_date_request = str(end_date_obj.replace( tzinfo=timezone.utc)).replace(" ", "T") while is_first or continue_search: if is_first: # performs the first search without next token search_response = keyword_spartial_search( query, start_date_request, end_date_request) is_first = False else: # Sleep for 3.1s per request because of twitter api limit time.sleep(3.1) search_response = keyword_spartial_search( query, start_date_request, end_date_request, next_token_) # insert the returned tweets from the response into an array compiling the searches extracted_tweet = extract_response_tweets(search_response) tweets = np.append(tweets, extracted_tweet) # insert the returned users from the response into an array compiling the searches extracted_users = extract_response_users(search_response) users = np.append(users, extracted_users) # insert the returned places from the response into an array compiling the searches extracted_places = extract_response_places(search_response) places = np.append(places, extracted_places) # insert the returned tweet info from the response into an array compiling the searches extracted_tweet_info = extract_response_tweets_info(search_response) tweet_infos = np.append(tweet_infos, extracted_tweet_info) # insert the returned response_errors from the response into an array compiling the searches extracted_response_errors = extract_response_errors(search_response) errors = np.append(errors, extracted_response_errors) # insert the returned medias from the response into an array compiling the searches extracted_response_media = extract_response_medias(search_response) media = np.append(media, extracted_response_media) # extract token next_token = extract_next_token(search_response) # check if search should continue continue_search = should_continue_search( len(tweets), number_of_tweets, next_token) return json.dumps(tweets.tolist()), json.dumps(users.tolist()), json.dumps(places.tolist()), json.dumps(tweet_infos.tolist()), json.dumps(errors.tolist()), json.dumps(media.tolist()) # connects to mongo db def connect_to_mongo(): # TODO add your updated mongodb connection string (!important) return MongoClient("") # send data to mongo db def send_to_mongo(dbname, dbcollection, data): client = connect_to_mongo() db = getattr(client, dbname) db_collection = getattr(db, dbcollection) db_collection.insert_one(data) # code execution point if __name__ == "__main__": # Catch exception and save the exceptions in mongo db try: # Keyword and spartial search => Similar to SQL boolean logic but nothing for AND. keyword_query = '(football OR "Manchester United" OR "<NAME>") lang:en' spatial_query = 'place_country:GB OR place_country:US' # search conditions, i.e, date span and number of tweet. If you want to use only date span, pass number of tweets as -1 or don't pass it at all start_date_request_ = '2015-08-15' end_date_request_ = '2020-08-17' number_of_tweets = 5000 # send the request and accept the response tweets, users, places, tweets_info, errors, media = retrieve_keyword_spartial(keyword_query, spatial_query, start_date_request_, end_date_request_, number_of_tweets) # compress the responses into a single dictionary object data = { "keyword": keyword_query, "spartial": spatial_query, "data": { "tweets": tweets, "users": users, "places": places, "tweets_info": tweets_info, "errors": errors, "media": media }, "was_successful": True } # save the response into a database dbname = "project" dbcollection = "tweets" send_to_mongo(dbname, dbcollection, data) except Exception as inst: data = { "keyword": keyword_query, "spartial": spatial_query, "data": {}, "was_successful": False, "exception": str(inst) } # save the response into a database dbname = "project" dbcollection = "tweets" send_to_mongo(dbname, dbcollection, data)
771fc39432837e71babe072738479f9ca16aa563
[ "Markdown", "Python" ]
2
Markdown
nuhu-ibrahim/Python-Twitter-V2-API-examples
c268d75b03221d630d2e7d3626238fce7d03071a
36e5d9d26ff2d7f9adb7cba5261d7e1592efd022
refs/heads/master
<repo_name>torans51/memory<file_sep>/src/types.js export const INIT_BOARD = 'INIT_BOARD'; export const INCREMENT_MOVE = 'INCREMENT_MOVE'; export const CHECK_FLIPPED_CARD = 'CHECK_FLIPPED_CARD'; export const FLIP_CARD = 'FLIP_CARD'; export const FLIP_CARD_TIMEOUT = 'FLIP_CARD_TIMEOUT'; export const CHECK_MATCH = 'CHECK_MATCH'; export const CHECK_BOARD = 'CHECK_BOARD'; export const NEW_GAME = 'NEW_GAME';<file_sep>/src/actions/board.js import * as types from "../types"; export const initBoard = () => ({ type: types.INIT_BOARD }); export const incrementMove = () => ({ type: types.INCREMENT_MOVE }); export const checkFlippedCard = cardId => ({ type: types.CHECK_FLIPPED_CARD, cardId }); export const flipCard = cardId => ({ type: types.FLIP_CARD, cardId }); export const flipCardTimeout = cardId => ({ type: types.FLIP_CARD_TIMEOUT, cardId: cardId }); export const checkMatch = () => ({ type: types.CHECK_MATCH }); export const checkBoard = () => ({ type: types.CHECK_BOARD }); <file_sep>/src/reducers/board.js import * as types from '../types'; import images from '../assets/images'; import { createRandomList } from '../utils/cardsUtil'; const initState = { moves: 0, win: false, flipTimeout: 5000, rows: 3, columns: 4, cards: [] }; export default function board(state = initState, action = {}) { switch (action.type) { case types.INIT_BOARD: return initBoard(state) case types.INCREMENT_MOVE: return incrementMove(state); case types.CHECK_FLIPPED_CARD: return checkFlippedCard(state, action); case types.FLIP_CARD: return flipCard(state, action); case types.FLIP_CARD_TIMEOUT: return flipCardTimeout(state, action); case types.CHECK_MATCH: return checkMatch(state); case types.CHECK_BOARD: return checkBoard(state); default: return state; } } function initBoard(state) { return { ...state, win: false, moves: 0, cards: createRandomList(images) }; } function incrementMove(state) { return { ...state, moves: state.moves + 1 }; } function checkFlippedCard(state, action) { const flippedCards = state.cards .filter(card => card.flipped && !card.matched && card.id !== action.cardId); if (flippedCards && flippedCards.length === 2) { const cards = state.cards.map(card => { if (flippedCards.includes(card)) { return { ...card, flipped: !card.flipped }; } return card; }); return { ...state, cards }; } return state; } function flipCard(state, action) { const cards = state.cards.map(card => { if (card.id === action.cardId) { return { ...card, flipped: !card.flipped }; } return card; }); return { ...state, cards }; } function flipCardTimeout(state, action) { const flippedCard = state.cards .find(card => card.id === action.cardId && card.flipped && !card.matched); if (flippedCard) { const cards = state.cards.map(card => { if (flippedCard === card) { return { ...card, flipped: false }; } return card; }); return { ...state, cards }; } return state; } function checkMatch(state) { const flippedCards = state.cards.filter(card => card.flipped && !card.matched); if (flippedCards && flippedCards.length === 2 && flippedCards[0].front === flippedCards[1].front) { const cards = state.cards.map(card => { if (flippedCards.includes(card)) { return { ...card, matched: true }; } return card; }); return { ...state, cards }; } return state; } function checkBoard(state) { const cardsLeft = state.cards.filter(card => !card.matched).length; return { ...state, win: cardsLeft === 0 }; }<file_sep>/src/utils/cardsUtil.js /** * Create a list of coupled shuffled cards given the images */ export const createRandomList = (images) => { const size = 2 * images.cardFrontImages.length; let availableImages = images.cardFrontImages.slice(); const cards = []; for (let i = 0; i < size; i += 2) { const image = availableImages.pop(); cards.push({ id: i, front: image, back: images.cardBackImage }, { id: i + 1, front: image, back: images.cardBackImage }); } return shuffle(cards); } /** * Create a new shuffled array from a given array */ function shuffle(array) { let a = array.slice(); let x, i, j; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; } <file_sep>/src/components/Score.js import React from 'react'; import { connect } from 'react-redux'; import { Container, Header } from 'semantic-ui-react'; class Score extends React.Component { render() { const { moves } = this.props; return ( <Container className="score"> <Header as='h1'>Moves</Header> <Header as='h1'>{moves}</Header> </Container> ) } } const mapStateToProps = (state) => ({ moves: state.board.moves }); export default connect(mapStateToProps, null)(Score);
2a5c93ee38ffb2a6c7f1e2d8c15bb5591579f59f
[ "JavaScript" ]
5
JavaScript
torans51/memory
e0cdac2cb8e1f387e0e889adeea96e568d7cb21f
ae73c57dfe0b9e7bef7fa95bf831928e1531b75a
refs/heads/master
<repo_name>alexcrichton/port-of-rust<file_sep>/i686-pc-windows-gnu/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update RUN apt-get -y install curl file gcc gcc-mingw-w64-i686 ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh i686-pc-windows-gnu RUN curl https://static.rust-lang.org/dist/rust-mingw-nightly-i686-pc-windows-gnu.tar.gz \ | tar xzvf - -C /tmp RUN /tmp/rust-mingw-nightly-i686-pc-windows-gnu/install.sh --prefix=`rustc --print sysroot` COPY i686-pc-windows-gnu/cargo-config /.cargo/config <file_sep>/x86_64-sun-solaris/Dockerfile FROM bgermann/port-prebuilt-solaris:2017-11-18 RUN apt-get -y update && apt-get -y install curl gcc ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh x86_64-sun-solaris COPY x86_64-sun-solaris/cargo-config /.cargo/config <file_sep>/README.md # Port of Rust [![Build Status](https://travis-ci.org/alexcrichton/port-of-rust.svg?branch=master)](https://travis-ci.org/alexcrichton/port-of-rust) This repo contains a collection of docker containers intended for compiling Rust code for various platforms. Each container contains what should be the bare minimum for compiling Rust code on the target platform, including: * A Rust compiler * A Rust standard library for the target platform * A C compiler/linker for the target platform The tests for this repository run a smoke "build a cargo project" for each platform, so at least "Hello, World!" should be guaranteed to work! ### Building an image First, figure out the target you'd like. Let's say that's `arm-linux-androideabi`. Next, build the docker container like so: ``` docker build -f arm-linux-androideabi/Dockerfile . ``` And then you're ready to go! ### Platform Support Most of the platforms here are currently untested, which means that your mileage may vary when using them. Some concerns to keep in mind when cross compiling are: * For Linux targets, the glibc version on the machine you run a binary on must be at least the glibc version in each docker container. Currently not much effort is done to ensure these glibc versions are "old", but patches are welcome! * For most other targets, they're compiled against "some version" of the OS being run on, and it may not always be the case that this version is old enough for you to run on your target platform. For example the Android container has an API level 21 toolchain, where the binaries of the standard library currently support API level 18. * Various codegen options for cross-compiled linux architectures may not always work out. Patches to the standard library and this repository are of course welcome! If those are all taken care of, however, then the cross compilation experience should be relatively smooth! # License These docker images are primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0), with portions covered by various BSD-like licenses. See LICENSE-APACHE, and LICENSE-MIT for details. <file_sep>/prebuilt/README.md # Prebuilt docker images Images in this directory take much longer (for whatever reason) to compile, so they're pushed up as intermediate artifacts. This allows us to test minor tweaks on Travis as well as facilitate downloads on smaller machines. All of these images are currently published under the tag: ``` alexcrichton/port-prebuilt-<name>:<date> ``` Where `<name>` is the name of the image and `<date>` is the date it was created. <file_sep>/arm-unknown-linux-gnueabihf/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update RUN apt-get -y install curl file gcc gcc-4.7-arm-linux-gnueabihf RUN ln -nsf /usr/bin/arm-linux-gnueabihf-gcc-4.7 \ /usr/bin/arm-linux-gnueabihf-gcc ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh arm-unknown-linux-gnueabihf COPY arm-unknown-linux-gnueabihf/cargo-config /.cargo/config <file_sep>/x86_64-unknown-linux-musl/docker-test.sh #!/bin/sh set -ex cargo new --bin foo (cd foo && cargo build) ldd foo/target/x86_64-unknown-linux-musl/debug/foo 2>&1 | grep 'not a dynamic' <file_sep>/powerpc-unknown-linux-gnu/Dockerfile FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y curl file gcc gcc-powerpc-linux-gnu ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh powerpc-unknown-linux-gnu COPY powerpc-unknown-linux-gnu/cargo-config /.cargo/config <file_sep>/x86_64-unknown-linux-gnu/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update RUN apt-get -y install curl file gcc ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=nightly COPY x86_64-unknown-linux-gnu/cargo-config /.cargo/config <file_sep>/arm-linux-androideabi/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update && apt-get -y install curl gcc file ENV PATH=$PATH:/android/ndk-arm/bin:/usr/local/cargo/bin \ CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup COPY support/android-install-ndk.sh /tmp/ RUN sh /tmp/android-install-ndk.sh \ --platform=android-21 \ --toolchain=arm-linux-androideabi-clang3.6 \ --install-dir=/android/ndk-arm \ --ndk-dir=android-ndk-r10e \ --arch=arm COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh arm-linux-androideabi COPY arm-linux-androideabi/cargo-config /.cargo/config <file_sep>/x86_64-unknown-linux-musl/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update RUN apt-get -y install curl file gcc musl-tools ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh x86_64-unknown-linux-musl COPY x86_64-unknown-linux-musl/cargo-config /.cargo/config <file_sep>/test.sh #!/bin/sh set -ex runtest() { target=$1 docker build -t port-of-rust-test -f $target/Dockerfile . docker run -e TARGET=$target -e USER=foo -i port-of-rust-test \ sh -s -- < ./docker-test.sh if [ -f $target/docker-test.sh ]; then docker run -e TARGET=$target -e USER=foo -i port-of-rust-test \ sh -s -- < $target/docker-test.sh fi } if [ -z "$1" ]; then echo "need a target to test" exit 1 elif [ "$1" = "all" ]; then for d in */Dockerfile; do target=$(dirname $d) runtest $target done else runtest $1 fi <file_sep>/prebuilt/netbsd/Dockerfile FROM ubuntu:16.04 RUN apt-get update -y && apt-get install -y --no-install-recommends \ curl \ ca-certificates \ make \ wget \ bzip2 \ g++ \ xz-utils \ zlib1g-dev COPY build-netbsd-toolchain.sh /tmp/ RUN /tmp/build-netbsd-toolchain.sh FROM ubuntu:16.04 COPY --from=0 /x-tools/ /x-tools ENV PATH=$PATH:/x-tools/x86_64-unknown-netbsd/bin \ AR_x86_64_unknown_netbsd=x86_64--netbsd-ar \ CC_x86_64_unknown_netbsd=x86_64--netbsd-gcc-sysroot \ CXX_x86_64_unknown_netbsd=x86_64--netbsd-g++-sysroot <file_sep>/support/android-install-ndk.sh #!/bin/sh set -ex curl -O http://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin chmod +x android-ndk-r10e-linux-x86_64.bin ./android-ndk-r10e-linux-x86_64.bin > /dev/null bash android-ndk-r10e/build/tools/make-standalone-toolchain.sh "$@" rm -rf ./android-ndk-r10e-linux-x86_64.bin ./android-ndk-r10e <file_sep>/x86_64-unknown-freebsd/Dockerfile FROM alexcrichton/port-prebuilt-freebsd:2017-09-16 RUN apt-get -y update && apt-get -y install curl gcc ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh x86_64-unknown-freebsd COPY x86_64-unknown-freebsd/cargo-config /.cargo/config <file_sep>/prebuilt/rumprun/Dockerfile FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y curl file g++ git make zlib1g-dev RUN git clone https://github.com/rumpkernel/rumprun WORKDIR /rumprun RUN git reset --hard <PASSWORD> RUN git submodule update --init RUN CC=cc ./build-rr.sh -d /usr/local hw WORKDIR / FROM ubuntu:16.04 COPY --from=0 /usr/local /usr/local <file_sep>/support/android-install-sdk.sh #!/bin/sh set -ex # Prep the SDK and emulator # # Note that the update process requires that we accept a bunch of licenses, and # we can't just pipe `yes` into it for some reason, so we take the same strategy # located in https://github.com/appunite/docker by just wrapping it in a script # which apparently magically accepts the licenses. mkdir sdk curl http://dl.google.com/android/android-sdk_r24.4-linux.tgz | \ tar xzf - -C sdk --strip-components=1 filter="platform-tools,android-18,android-21" filter="$filter,sys-img-x86-android-18" filter="$filter,sys-img-x86_64-android-18" filter="$filter,sys-img-armeabi-v7a-android-18" filter="$filter,sys-img-x86-android-21" filter="$filter,sys-img-x86_64-android-21" filter="$filter,sys-img-armeabi-v7a-android-21" ./accept-licenses.sh "android - update sdk -a --no-ui --filter $filter" echo "no" | android create avd \ --name arm-18 \ --target android-18 \ --abi armeabi-v7a echo "no" | android create avd \ --name arm-21 \ --target android-21 \ --abi armeabi-v7a echo "no" | android create avd \ --name x86-21 \ --target android-21 \ --abi x86 echo "no" | android create avd \ --name x86_64-21 \ --target android-21 \ --abi x86_64 <file_sep>/powerpc64le-unknown-linux-gnu/Dockerfile FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y curl file gcc gcc-powerpc64le-linux-gnu ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh powerpc64le-unknown-linux-gnu COPY powerpc64le-unknown-linux-gnu/cargo-config /.cargo/config <file_sep>/prebuilt/freebsd/build-toolchain.sh #!/bin/bash # Copyright 2016 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. set -ex ARCH=x86_64 BINUTILS=2.25.1 GCC=6.4.0 hide_output() { set +x on_err=" echo ERROR: An error was encountered with the build. cat /tmp/build.log exit 1 " trap "$on_err" ERR bash -c "while true; do sleep 30; echo \$(date) - building ...; done" & PING_LOOP_PID=$! $@ &> /tmp/build.log trap - ERR kill $PING_LOOP_PID set -x } cd /tmp mkdir binutils cd binutils # First up, build binutils curl https://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS.tar.bz2 | tar xjf - mkdir binutils-build cd binutils-build hide_output ../binutils-$BINUTILS/configure \ --target=$ARCH-unknown-freebsd10 hide_output make -j10 hide_output make install cd ../.. rm -rf binutils # Next, download the FreeBSD libc and relevant header files mkdir freebsd case "$ARCH" in x86_64) URL=ftp://ftp.freebsd.org/pub/FreeBSD/releases/amd64/10.2-RELEASE/base.txz ;; i686) URL=ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/10.2-RELEASE/base.txz ;; esac curl $URL | tar xJf - -C freebsd ./usr/include ./usr/lib ./lib dst=/usr/local/$ARCH-unknown-freebsd10 cp -r freebsd/usr/include $dst/ cp freebsd/usr/lib/crt1.o $dst/lib cp freebsd/usr/lib/Scrt1.o $dst/lib cp freebsd/usr/lib/crti.o $dst/lib cp freebsd/usr/lib/crtn.o $dst/lib cp freebsd/usr/lib/libc.a $dst/lib cp freebsd/usr/lib/libutil.a $dst/lib cp freebsd/usr/lib/libutil_p.a $dst/lib cp freebsd/usr/lib/libm.a $dst/lib cp freebsd/usr/lib/librt.so.1 $dst/lib cp freebsd/usr/lib/libexecinfo.so.1 $dst/lib cp freebsd/lib/libc.so.7 $dst/lib cp freebsd/lib/libm.so.5 $dst/lib cp freebsd/lib/libutil.so.9 $dst/lib cp freebsd/lib/libthr.so.3 $dst/lib/libpthread.so ln -s libc.so.7 $dst/lib/libc.so ln -s libm.so.5 $dst/lib/libm.so ln -s librt.so.1 $dst/lib/librt.so ln -s libutil.so.9 $dst/lib/libutil.so ln -s libexecinfo.so.1 $dst/lib/libexecinfo.so rm -rf freebsd # Finally, download and build gcc to target FreeBSD mkdir gcc cd gcc curl https://ftp.gnu.org/gnu/gcc/gcc-$GCC/gcc-$GCC.tar.gz | tar xzf - cd gcc-$GCC ./contrib/download_prerequisites mkdir ../gcc-build cd ../gcc-build hide_output ../gcc-$GCC/configure \ --enable-languages=c,c++ \ --target=$ARCH-unknown-freebsd10 \ --disable-multilib \ --disable-nls \ --disable-libgomp \ --disable-libquadmath \ --disable-libssp \ --disable-libvtv \ --disable-libcilkrts \ --disable-libada \ --disable-libsanitizer \ --disable-libquadmath-support \ --disable-lto hide_output make -j10 hide_output make install cd ../.. rm -rf gcc <file_sep>/support/install-rust.sh curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=nightly rustup target add $1 <file_sep>/arm-unknown-linux-gnueabi/Dockerfile FROM ubuntu:16.04 RUN apt-get -y update RUN apt-get -y install curl file gcc gcc-4.7-arm-linux-gnueabi RUN ln -nsf /usr/bin/arm-linux-gnueabi-gcc-4.7 \ /usr/bin/arm-linux-gnueabi-gcc ENV CARGO_HOME=/usr/local/cargo \ RUSTUP_HOME=/usr/local/rustup \ PATH=/usr/local/cargo/bin:$PATH COPY support/install-rust.sh /tmp/ RUN sh /tmp/install-rust.sh arm-unknown-linux-gnueabi COPY arm-unknown-linux-gnueabi/cargo-config /.cargo/config <file_sep>/prebuilt/freebsd/Dockerfile FROM ubuntu:16.04 RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ make \ curl \ ca-certificates \ bzip2 \ xz-utils \ wget \ pkg-config COPY build-toolchain.sh /tmp/ RUN /tmp/build-toolchain.sh FROM ubuntu:16.04 COPY --from=0 /usr/local /usr/local ENV CC_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-gcc \ CXX_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-g++ \ AR_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-ar \ <file_sep>/docker-test.sh #!/bin/sh set -ex cargo new testlib (cd testlib && cargo build) rm testlib/target/$TARGET/debug/libtestlib.rlib cargo new testbin --bin cat > testbin/Cargo.toml <<-EOF [project] name = "testbin" version = "0.1.0" authors = [] build = "build.rs" [build-dependencies] gcc = "0.3" EOF cat > testbin/build.rs <<-EOF extern crate gcc; fn main() { gcc::Build::new().file("foo.c").compile("libfoo.a"); } EOF cat > testbin/foo.c <<-EOF #include <stdio.h> #include <stdlib.h> void foo() { } EOF cat > testbin/src/main.rs <<-EOF extern { fn foo(); } fn main() { unsafe { foo(); } } EOF (cd testbin && cargo build) file=testbin/target/$TARGET/debug/testbin if [ -f $file.exe ]; then rm $file.exe else rm $file fi
4caac39443bfb441a9b1dbfd83b96f69a2cb4c8b
[ "Markdown", "Dockerfile", "Shell" ]
22
Dockerfile
alexcrichton/port-of-rust
bab3fda2e923170d294a8dc3ed5737a49fa66920
083636873bda3cd849950f214f50c529ae52036a
refs/heads/master
<file_sep>package com.basic_demo.Activity; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import com.basic_demo.R; import com.basic_demo.ViewModels.ListViewModel; import com.basic_demo.adapter.MyDataAdapter; import com.basic_demo.databinding.ActivityMainBinding; import com.basic_demo.models.Example; import java.util.List; public class MainActivity extends AppCompatActivity { ActivityMainBinding binding; ListViewModel listViewModel; LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); MyDataAdapter myDataAdapter; List<Example> maindata; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_main); binding.llPgbar.setVisibility(View.VISIBLE); ListViewModel.Factory factory = new ListViewModel.Factory(getApplication(), ""); listViewModel = ViewModelProviders.of(MainActivity.this, factory).get(ListViewModel.class); linearLayoutManager.setOrientation(RecyclerView.VERTICAL); binding.rvNews.setLayoutManager(linearLayoutManager); observeViewModel(); } private void observeViewModel() { listViewModel.getObservable().observe(this, new Observer<List<Example>>() { @Override public void onChanged(List<Example> examples) { binding.llPgbar.setVisibility(View.GONE); maindata = examples; myDataAdapter = new MyDataAdapter(maindata,MainActivity.this); binding.rvNews.setAdapter(myDataAdapter); } }); } }
04188023d1e873d8d6705d905c273e573e42dbcd
[ "Java" ]
1
Java
Prajwalpraju3/BASIC_MVVM
93889444673060db7370f8c746e40c7b107e817e
9f7d3a8ef2f26de76db773b80b2290cbac00172e
refs/heads/master
<file_sep>package com.kaungmyatmin.haulio.common.baseclass; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public abstract class BaseViewHolder<T> extends RecyclerView.ViewHolder { public BaseViewHolder(@NonNull View itemView) { super(itemView); bindViews(itemView); } protected abstract void bindViews(View view); protected abstract void bindData(T t); } <file_sep>package com.kaungmyatmin.haulio.common.dependancyInjection.activity; import android.content.Context; import android.view.LayoutInflater; import androidx.fragment.app.FragmentManager; import com.kaungmyatmin.haulio.common.baseclass.BaseActivity; import com.kaungmyatmin.haulio.helper.NavigationHelper; import dagger.Module; import dagger.Provides; @Module public class ActivityModule { private final BaseActivity mActivity; public ActivityModule(BaseActivity activity) { mActivity = activity; } @Provides BaseActivity getActivity() { return this.mActivity; } @Provides static Context getContext(BaseActivity activity) { return activity; } @Provides static FragmentManager getFragmentManager(BaseActivity activity) { return activity.getSupportFragmentManager(); } @Provides static LayoutInflater getLayoutInflater(Context context) { return LayoutInflater.from(context); } @Provides static NavigationHelper getNavigationHelper(BaseActivity activity){ return new NavigationHelper(activity); } } <file_sep>package com.kaungmyatmin.haulio.network; import com.kaungmyatmin.haulio.model.Job; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface ApiService { String API_VERSION = "bins/"; @GET(API_VERSION + "8d195") Call<List<Job>> getJobs(); }<file_sep>package com.kaungmyatmin.haulio.helper; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.navigation.NavController; import androidx.navigation.Navigation; import com.kaungmyatmin.haulio.R; import com.kaungmyatmin.haulio.model.Job; /** * This class handle all the navigation of the application * Noted: Using this class inside view model and * inside any kind of async task may cause * memory leak as this class cache activity */ public class NavigationHelper { private Activity activity; public NavigationHelper(Activity activity) { this.activity = activity; } public void toSplash() { getNavController().popBackStack(R.id.dest_splashFragment, false); } public void toLogin() { NavController navController = getNavController(); navController.popBackStack(R.id.dest_splashFragment, true); navController.navigate(R.id.dest_loginFragment); } public void toJobs() { NavController controller = getNavController(); controller.popBackStack(); controller.navigate(R.id.dest_jobsFragment); } public void toTransport(Job job) { Bundle bundle = new Bundle(); bundle.putSerializable("job", job); getNavController() .navigate(R.id.dest_transportFragment, bundle); } public void restartApplication() { Intent i = activity.getPackageManager() .getLaunchIntentForPackage(activity.getPackageName()); activity.startActivity(i); activity.finishAffinity(); } public void exitApplication(){ activity.finishAndRemoveTask(); } private NavController getNavController() { return Navigation.findNavController(activity, R.id.nav_host_fragment); } } <file_sep>package com.kaungmyatmin.haulio.ui.login; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.kaungmyatmin.haulio.common.baseclass.BaseViewModel; import com.kaungmyatmin.haulio.model.User; import javax.inject.Inject; public class LoginViewModel extends BaseViewModel { public enum AuthenticationState { UNAUTHENTICATED, // Initial state, the user needs to authenticate AUTHENTICATED, // The user has authenticated successfully INVALID_AUTHENTICATION // Authentication failed } private MutableLiveData<AuthenticationState> authenticationState; @Inject public LoginViewModel() { init(); } @Override protected void init() { authenticationState = new MutableLiveData<>(); } public void authenticate(User user) { //todo: implement authentication user at the backend //now we authenticate user with google authenticationState.setValue(AuthenticationState.AUTHENTICATED); } public void authenticateFail(){ //todo: this method should be remove in later version, combine this method with authenticate(User user) method authenticationState.setValue(AuthenticationState.INVALID_AUTHENTICATION); } public void refuseAuthentication() { authenticationState.setValue(AuthenticationState.UNAUTHENTICATED); } //------- getter and setter ------- public LiveData<AuthenticationState> getAuthenticationState() { return authenticationState; } } <file_sep>package com.kaungmyatmin.haulio.common.constant; /* Holder of various constants. Modified constants according to MyConfig. */ public final class Constant implements MyConfig, MyKeys, MyUrls { public static final String BASE_URL = IS_PRODUCTION ? URL_PRODUCTION : URL_STAGING; } <file_sep>package com.kaungmyatmin.haulio.ui.login; import android.content.Intent; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.kaungmyatmin.haulio.R; import com.kaungmyatmin.haulio.common.baseclass.BaseFragment; import com.kaungmyatmin.haulio.helper.AuthHelper; import com.kaungmyatmin.haulio.helper.MyLog; import com.kaungmyatmin.haulio.helper.NavigationHelper; import com.kaungmyatmin.haulio.model.User; import javax.inject.Inject; public class LoginFragment extends BaseFragment { private static final String TAG = LoginFragment.class.getSimpleName(); private static final int RC_SIGN_IN = 1123; private User user; private Button signInButton; @Inject LoginViewModel mViewModel; @Inject AuthHelper authHelper; @Inject NavigationHelper navigationHelper; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_login, container, false); bindViews(view); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setListeners(); getActivityComponent().inject(this); setObservers(); } @Override protected void bindViews(View view) { signInButton = view.findViewById(R.id.sign_in_button); } @Override protected void setListeners() { signInButton.setOnClickListener(view -> { startSignInProcess(); }); requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { mViewModel.refuseAuthentication(); } }); } @Override protected void setObservers() { mViewModel.getAuthenticationState().observe(getViewLifecycleOwner(), authenticationState -> { switch (authenticationState) { case AUTHENTICATED: authHelper.save(user); navigationHelper.toSplash(); break; case UNAUTHENTICATED: navigationHelper.exitApplication(); break; case INVALID_AUTHENTICATION: Snackbar.make(getView(), R.string.invalid_credentials, Snackbar.LENGTH_SHORT ).show(); break; } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } } private void startSignInProcess() { Intent signInIntent = authHelper.getGoogleSignInClient(getActivity()).getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); user = new User(); user.setName(account.getDisplayName()); user.setProfilePic(account.getPhotoUrl().toString()); user.setId(account.getEmail()); mViewModel.authenticate(user); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. mViewModel.authenticateFail(); } } } <file_sep>include ':app' rootProject.name='Haulio' <file_sep># Haulio A test mobile app for the truck drivers to help them easily find the nearby important places, such as restaurants and parking places while they are driving to do their allocated jobs. ### Screenshots | Login Screen | Choosing Account | Loading Jobs| | ------ | ------ | ------ | |<img alt="Login" title="Login" src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/1.new_user.png" width="200"> | <img src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/2.choose_account.png" width="200">|<img src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/3.loading.png" width="200">| | Jobs List | Transporting | Searching Places| | ------ | ------ | ------ | |<img src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/4.jobs.png" width="200">|<img src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/5.transport.png" width="200">|<img src="https://github.com/KaungMyat-Min/haulio/blob/master/screenshots/6.search.png" width="200">| ### Main Technology | Tech | Feature/Purpose | | ------ | ------ | | Java | Main Language | | Dagger2 | Dependency Injection | | MVVM | Pattern | | LiveData | Reactive | | Play Service | Map api and google login | | Navigation Conponent | In app navigation | | Retrofit2 | RESTful | | Picasso | ImageLoading | <file_sep>package com.kaungmyatmin.haulio.ui.transport; import android.location.Location; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.tasks.Task; import com.kaungmyatmin.haulio.common.baseclass.BaseViewModel; import javax.inject.Inject; public class TransportViewModel extends BaseViewModel { private MutableLiveData<Location> currentLocation; @Inject public TransportViewModel() { init(); } @Override protected void init() { currentLocation = new MutableLiveData<>(); } public void fetchCurrentLocation(FusedLocationProviderClient locationProviderClient){ Task<Location> task = locationProviderClient.getLastLocation(); task.addOnSuccessListener(location -> { if (location != null) { currentLocation.postValue(location); } }); } //----------- getter and setter ----------- public LiveData<Location> getCurrentLocation(){ return this.currentLocation; } } <file_sep>package com.kaungmyatmin.haulio.common.dependancyInjection.activity; import androidx.lifecycle.ViewModel; import com.kaungmyatmin.haulio.ui.login.LoginViewModel; import com.kaungmyatmin.haulio.ui.jobs.JobsViewModel; import com.kaungmyatmin.haulio.ui.splash.SplashViewModel; import com.kaungmyatmin.haulio.ui.transport.TransportViewModel; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import dagger.Binds; import dagger.MapKey; import dagger.Module; import dagger.multibindings.IntoMap; @Module public abstract class ViewModelModule { @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @MapKey @interface ViewModelKey { Class<? extends ViewModel> value(); } @Binds @IntoMap @ViewModelKey(JobsViewModel.class) abstract ViewModel provideJobsViewModel(JobsViewModel viewModel); @Binds @IntoMap @ViewModelKey(TransportViewModel.class) abstract ViewModel provideTransportViewModel(TransportViewModel viewModel); @Binds @IntoMap @ViewModelKey(LoginViewModel.class) abstract ViewModel provideLoginViewModel(LoginViewModel viewModel); @Binds @IntoMap @ViewModelKey(SplashViewModel.class) abstract ViewModel provideSplashViewModel(SplashViewModel viewModel); } <file_sep>package com.kaungmyatmin.haulio.common.dependancyInjection.activity; import com.kaungmyatmin.haulio.MainActivity; import com.kaungmyatmin.haulio.ui.login.LoginFragment; import com.kaungmyatmin.haulio.ui.jobs.JobsFragment; import com.kaungmyatmin.haulio.ui.splash.SplashFragment; import com.kaungmyatmin.haulio.ui.transport.TransportFragment; import dagger.Subcomponent; @Subcomponent(modules = {ActivityModule.class, ViewModelModule.class}) public interface ActivityComponent { void inject(MainActivity loginFragment); void inject(JobsFragment jobsFragment); void inject(TransportFragment transportFragment); void inject(LoginFragment loginFragment); void inject(SplashFragment splashFragment); } <file_sep>package com.kaungmyatmin.haulio.model; import com.kaungmyatmin.haulio.errorhandler.ErrorType; public class DataWrapper<T> { private T data; private ErrorType errorType; private boolean isLoading; public DataWrapper(T data, ErrorType errorType, boolean isLoading) { this.data = data; this.errorType = errorType; this.isLoading = isLoading; } public T getData() { return data; } public void setData(T data) { this.data = data; } public ErrorType getErrorType() { return errorType; } public void setErrorType(ErrorType errorType) { this.errorType = errorType; } public boolean isLoading() { return isLoading; } public void setLoading(boolean loading) { isLoading = loading; } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.kaungmyatmin.haulio" minSdkVersion 26 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } } ext { dagger = '2.21' androidx = '1.1.0' lifecycle = '2.1.0' navigation = '2.1.0' constraintLayout = '1.1.3' cardview = '1.0.0' recyclerview = '1.1.0' material = '1.0.0' retrofit = '2.7.1' picasso = '2.71828' playservice = '17.0.0' places = '2.1.0' } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) //------------------- androidx ------------------- implementation "androidx.appcompat:appcompat:$androidx" implementation "androidx.constraintlayout:constraintlayout:$constraintLayout" implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle" implementation "androidx.recyclerview:recyclerview:$recyclerview" implementation "androidx.navigation:navigation-fragment:$navigation" implementation "androidx.navigation:navigation-ui:$navigation" implementation "androidx.cardview:cardview:$cardview" implementation "com.google.android.material:material:$material" //------------------- Map ------------------- implementation "com.google.android.gms:play-services-maps:$playservice" implementation "com.google.android.gms:play-services-location:$playservice" implementation "com.google.android.libraries.places:places-compat:$places" implementation "com.google.android.gms:play-services-auth:$playservice" //------------------- Retrofit2 ------------------- implementation "com.squareup.retrofit2:retrofit:$retrofit" implementation "com.squareup.retrofit2:converter-gson:$retrofit" implementation "com.squareup.picasso:picasso:$picasso" // implementation 'com.github.florent37:picassopalette:2.0.0' //------------------- dagger2 ------------------- implementation "com.google.dagger:dagger:${dagger}" implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0' annotationProcessor "com.google.dagger:dagger-compiler:${dagger}" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' } <file_sep>package com.kaungmyatmin.haulio; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.Toolbar; import androidx.navigation.NavController; import androidx.navigation.Navigation; import com.kaungmyatmin.haulio.common.baseclass.BaseActivity; import com.kaungmyatmin.haulio.helper.AuthHelper; import com.kaungmyatmin.haulio.helper.MyLog; import com.kaungmyatmin.haulio.helper.NavigationHelper; import javax.inject.Inject; public class MainActivity extends BaseActivity { private static final String TAG = MainActivity.class.getSimpleName(); //--------- view variable start --------- private AppCompatImageButton ibBack, ibLogout; private Toolbar toolbar; private ActionBar actionBar; //-------- view variable end --------- @Inject AuthHelper authHelper; @Inject NavigationHelper navigationHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); getActivityComponent().inject(this); bindViews(); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); setListeners(); } @Override protected void bindViews() { toolbar = findViewById(R.id.toolbar); ibLogout = toolbar.findViewById(R.id.action_log_out); ibBack = toolbar.findViewById(R.id.action_back); } @Override protected void setListeners() { ibLogout.setOnClickListener(view -> { authHelper.logout(this); navigationHelper.restartApplication(); }); ibBack.setOnClickListener(view -> { onBackPressed(); }); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); navController.addOnDestinationChangedListener((controller, destination, arguments) -> { switch (destination.getId()) { case R.id.dest_loginFragment: actionBar.hide(); break; case R.id.dest_jobsFragment: toolbar.findViewById(R.id.action_back).setVisibility(View.INVISIBLE); actionBar.show(); break; default: toolbar.findViewById(R.id.action_back).setVisibility(View.VISIBLE); actionBar.show(); } }); } } <file_sep>package com.kaungmyatmin.haulio.ui.splash; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.kaungmyatmin.haulio.R; import com.kaungmyatmin.haulio.common.baseclass.BaseFragment; import com.kaungmyatmin.haulio.helper.AuthHelper; import com.kaungmyatmin.haulio.helper.NavigationHelper; import com.kaungmyatmin.haulio.model.User; import javax.inject.Inject; public class SplashFragment extends BaseFragment { @Inject SplashViewModel mViewModel; @Inject AuthHelper authHelper; @Inject NavigationHelper navigationHelper; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_splash, container, false); bindViews(view); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getActivityComponent().inject(this); if(authHelper.isLogged()){ navigationHelper.toJobs(); }else { navigationHelper.toLogin(); } setListeners(); setObservers(); } @Override protected void bindViews(View view) { } @Override protected void setListeners() { } @Override protected void setObservers() { } } <file_sep>package com.kaungmyatmin.haulio.common.constant; interface MyConfig { int SPLASH_DURATION_MILLISECOND = 1000; boolean IS_PRODUCTION = false; int MAP_ZOOM_SIZE = 12; } <file_sep>package com.kaungmyatmin.haulio.errorhandler; import android.app.Activity; import android.widget.Toast; public final class MyErrorHandler { public static void showToast(Activity activity, ErrorType errorType) { Toast.makeText(activity, errorType.getStringResId(), Toast.LENGTH_LONG).show(); } }
a741f2ad3aa2a4656f5b8ec730091ec4a84a6f07
[ "Markdown", "Java", "Gradle" ]
18
Java
KaungMyat-Min/haulio
0bddf5e14b518dd12254d8963867426c9450467b
e3984a0f128ab10177087dfe61862e9f2bff771c
refs/heads/master
<file_sep># Python_Programs This contains some programs written in Python language. <file_sep>d1={1:'a',2:'b',3:'c'} print(d1) d2={1:'a',2:'b',3:'c'} print(d2) cmp(d1,d2)
99cffde4070ed59be24e337629b361f749e0e1d3
[ "Markdown", "Python" ]
2
Markdown
muskangupta19/Python_Programs
24f67fba25b2db8b4afdefa564c7f41ef816688e
db36297df04cb4b3f9d480209f7926a579b5e26b
refs/heads/master
<repo_name>TriDianaRimadhani/Praktikum5-PHPPemweb<file_sep>/ceklogin.php <?php include "akun.php"; //file juga mengambil file akun.php untuk dieksekusi disini //kondisi untuk mengecek inputan dari form dengan variable yang telah dideklarasi if ($_POST['username']==$username){ //variabel username diambil dari akun.php if ($_POST['email']==$email){ //variabel email diambil dari akun.php header ("Location:index.php"); //jika inputan form username dan email sama dengan variabel, maka akan diarahkan pada halaman index.php } else { header("Location:logkosongemail.php");//jika data email kosong/salah maka akan diarahkan ke logkosongemail.php } } else { header("Location:logkosonguser.php");//jika username kosong/salah maka akan diarahkan ke logkosonguser.php } ?><file_sep>/array.php <html> <head> <title> Pemrograman PHP dengan Array </title> </head> <body> <?php //penulisan array dapat dibuat seperti berikut //pendeklarasian variabel menggunakan array $nama[] = "Dhani"; $nama[] = "Laras"; $nama[] = "Eni"; //menampilkan urutan array yang dipanggil sesuai indeks echo $nama[1], "<br>" . $nama[2], "<br>" . $nama[0]; echo "<br>"; //menghitung jumlah elemen array $jum_array = count($nama); //menampilkan jumlah elemen array echo "Jumlah elemen array = " . $jum_array; ?> </body> </html><file_sep>/index.php <!DOCTYPE html> <html> <head> <title>Home</title> <!--menyambungkan pada file css--> <link rel="stylesheet" type="text/css" href="style.css"> </head> <style> /*style tampilan untuk h1*/ h1 { background-color:transparent; color: rgb(62, 112, 179); font-family:sans-serif; text-align: center; width: 45%; margin-top: 10%; margin-right:auto; margin-left:auto; padding: 20px; border: 3px solid #333281 } /*menyisipkan background untuk halaman*/ body { background-image: url('abstract-watercolor-background_91008-101.jpg'); background-repeat: no-repeat; background-size:cover; } /*tampilan css untuk area div*/ div{ margin-top:10%; margin-right:60%; margin-left:1cm; width: 250px; border:1px solid #4745e2; } </style> <body> <nav class="nav"><!--tag nav telah di definisikan style tampilannya--> <ul><!--script untuk pembuatan menu/navigasi bar--> <li><a href ="http://localhost/praktikum5/contact.php">Contact</a></li> <li><a href ="http://localhost/praktikum5/interest.php">Interest</a></li> <li><a href ="http://localhost/praktikum5/profile.php">Profile</a></li> <li><a href ="http://localhost/praktikum5/index.php">Home</a></li> </ul> </nav> <h1>WELCOME TO MY PAGE</h1> <div> <?php include "akun.php"; //menggunakan include dengan file akun.php untuk dieksekusi disini echo "<center>Log Activity</center>","<br>"; //menampilkan variabel dari file akun.php echo "Nama :".$username."<br>"; echo "Email :".$email."<br>"; //menampilkan waktu login echo date ("d-D-F-Y, g:i:s a"); ?> </div> </body> </html><file_sep>/date.php <html> <head> <title> Tanggalan </title> </head> <body> <?php date_default_timezone_set("Asia/Jakarta"); //setting default timezone untuk waktu di Indonesia //menampilkan bulan ke-,bulan, tahun, jam, menit, detik dengan waktu AM echo date ("m-F-Y, g:i:s a"); ?> </body> </html><file_sep>/cekcookies.php <?php //menggunakan kondisi untuk mengeksekusi operasi if (isset($variable_cookies)) { //menampilkan variabel cookies yng telah dideklarasikan echo 'Variabel cookiesnya "$variable_cookies" nilainya adalah' . $variable_cookies; } else{ //jika variabel belum dideklarasikan akan muncul teks echo "Variabel cookies belum diterapkan"; } ?><file_sep>/kosong.php <?php //jika data form kosong maka user akan di dipindahkan di halaman ini //menampilkan teks dalam petik echo "Data Kosong"; ?><file_sep>/inc.php <?php //pendeklarasian variabel angka $angka=90; ?><file_sep>/tes.php <?php header ("Location:destination.php")//penghubung redirect dari halaman redirect.html ?><file_sep>/konversitipedata.php <html> <head> <title> Konversi Tipe Data </title> </head> <body> <?php //pendeklarasian variabel a $a = 300.4; //menampilkan variabel a echo $a; //spasi satu baris echo "<br>"; //variabel a dikonversi menjadi tipe double echo "Tipe Double :", doubleval($a), "<br>"; //variabel a dikonversi menjadi tipe integer echo "Tipe Integer :",intval($a), "<br>"; //variabel a dikonversi menjadi tipe string echo "Tipe String :", strval($a) ?> </body> </html><file_sep>/proses.php <?php include "inc.php"; //include berfungsi mengambil dari file lain yang kan di eksekusi juga disini echo $angka; //variabel angka yang telah dideklarasikan di file inc.php echo "<br>"; //operasi kondisi untuk eksekusi dari variabel yang telah diambil if ($angka==100){ echo "Memuaskan"; } elseif ($angka<100&&$angka>=85) { echo "Sangat Baik"; } elseif ($angka<85&&$angka>=70) { echo "Baik"; } elseif ($angka<70&&$angka>=55) { echo "Cukup"; } elseif($angka<55&&$angka>=0) { echo "Kurang"; } ?><file_sep>/logkosongemail.php <html><!--halaman ketika email kosong--> <head> <!--menyambungkan dengan file css--> <link rel="stylesheet" type="text/css" href="style.css"> </head> <style> /*style untuk area div*/ div{ margin: 15% auto; width: 400px; border:2px solid #c70505; } </style> <div> <?php //menampilkan teks echo "<center>Data tidak lengkap</center>","<br>"; echo "<center>Anda tidak memasukkan email anda atau email anda salah!</center>"; ?> <!--tombol untuk kembali pada halaman login--> <center><a href="http://localhost/praktikum5/login.php"><button class="button">Kembali</button></a></center> </div> </html><file_sep>/trial_1.php <html> <head> <title> Variabel </title> </head> <body> <?php //pendeklarasian variabel nilai_1,nilai_2 dan nilai_3 $nilai_1 = 10; $nilai_2 = 3; //pendeklarasian variabel menggunakan operasi matematika $nilai_3 = 2 * $nilai_1 + 8 * $nilai_2; //menampilkan variabel echo "nilai = ", $nilai_3; echo "<br>"; //pendeklarasian variabel dengan operasi matematika $jumlah = $nilai_1 + $nilai_2; echo "Hasil dari $nilai_1 + $nilai_2 adalah $jumlah"; echo "<br><br>"; //menampilkan sebuah teks echo "\"Nama : <NAME>\" <br>"; echo "NPM : 19082010050"; ?> </body> </html><file_sep>/destination.php <?php echo "Redirect Tujuan"//tujuan dari redirect ?><file_sep>/akun.php <?php //pendeklarasian variabel username dan email $username="dianarima"; $email="<EMAIL>"; ?><file_sep>/postAct.php <?php //hasil dari inputan form dari halaman post.php //mengambil inputan username dari form echo "<center>Nama :".$_POST['name']."</center><br>"; //mengambil inputan email dari form echo "<center>Email :".$_POST['email']."</center><br>"; ?><file_sep>/linkcookies.php <?php //mendeklarasikan variabel pada cookies setcookie("variable_cookies","Ini adalah variabel cookies", time()+60); //link untuk menuju halaman cekookies echo "<a href=cekcookies.php>Cek Cookies</a>"; ?><file_sep>/hasilkirim.php <?php //hasil dari inputan form akan dikirim disini if (empty($_POST['nama'])){ header("Location:kosong.php"); //jika inputan tidak ada data, akan di direct ke halaman kosong.php } else { //menampilkan variabel dari POST yang telah diambil dari form dengan method="POST" echo "<center>Nama :".$_POST['nama']."</center><br>"; } ?><file_sep>/logkosonguser.php <html> <head> <!--menghubungkan dengan file style.css--> <link rel="stylesheet" type="text/css" href="style.css"> </head> <style> div{ /*pengaturan tampilan untuk area div*/ margin: 15% auto; width: 400px; border:2px solid #c70505; } </style> <div> <?php //menampilkan teks dengan posisi di tengah echo "<center>Data tidak lengkap</center>","<br>"; echo "<center>Anda tidak memasukkan username anda atau username anda salah!</center>"; ?> <!--tombol 'Kembali' untuk diarahkan kembali ke halaman login.php dengan tampilan css--> <center><a href="http://localhost/praktikum5/login.php"><button class="button" >Kembali</button></a></center> </div> </html>
1718cf925a54e96699b81e716584a2e0fa8b0036
[ "PHP" ]
18
PHP
TriDianaRimadhani/Praktikum5-PHPPemweb
c5d8e81f33f03a3ee3023d1c4c5fb8180918f17d
349e12a441304ba2c8ccc9cf691f637a4bf22a14
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPG.Core { class Ennemie:Entity,ISoignable,IAttaquable { public void Soigner(int PvGagner) { _pvActuel = _pvActuel + PvGagner; } public void PrendreDegats(int DegatsSubis) { _pvActuel = _pvActuel - (DegatsSubis - _armure/2); } public Ennemie(int pvMax, int manaMax, int force, int intel, int armure, string nom, int level, int degatPhysique, int degatMagique) : base(pvMax, manaMax, force, intel, armure, nom, level) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenTK.Graphics.OpenGL; namespace RPG.Core.Items { public enum TypeItemUtilisable { soin, degat } class ItemUtilisable : Item { private TypeItemUtilisable _typeItemUtilisable; private int _effect; public TypeItemUtilisable TypeItemUtilisable { get { return _typeItemUtilisable; } } public int Effect { get { return _effect;} } public ItemUtilisable (string nom, string description, int effect, TypeItemUtilisable typeItemUtilisable) : base(nom, description) { _effect = effect; _typeItemUtilisable = typeItemUtilisable; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using OpenTK.Graphics.OpenGL; namespace RPG.Core.Items { public enum TypeItemEquipable { Tete, Torse, Jamble, Pied, Arme1Main, Arme2Main, Bouclier } class ItemEquipable : Item { private TypeItemEquipable _typeItemEquipable; private int _pv; private int _mana; private int _degatPhysique; private int _degatMagique; private int _armure; public int Pv { get { return _pv;} } public int Mana { get { return _mana;} } public int DegatPhysique { get { return _degatPhysique;} } public int DegatMagique { get { return _degatMagique;} } public int Armure { get { return _armure; } } public ItemEquipable(string nom, string description, int pv, int mana, int degatPhysique, int degatMagique, int armure, TypeItemEquipable typeItemEquipable) : base(nom, description) { _pv = pv; _mana = mana; _degatPhysique = degatPhysique; _degatMagique = degatMagique; _armure = armure; _typeItemEquipable = typeItemEquipable; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPG.Core { interface IAttaquable { void PrendreDegats(int DegatsSubis); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPG.Core { class Joueur:Entity,IAttaquable,ISoignable { private int _degatPhysique; private int _degatMagique; public int DegatPhysique { get { return _degatPhysique; } } public int DegatMagique { get { return _degatMagique; } } public void Soigner(int PvGagner) { _pvActuel = _pvActuel + PvGagner; } public void PrendreDegats(int DegatsSubis) { _pvActuel = _pvActuel - (DegatsSubis - _armure/2); } public Joueur(int pvMax, int manaMax, int force, int intel, int armure, string nom, int level, int degatPhysique, int degatMagique) : base(pvMax, manaMax, force, intel, armure, nom, level) { _degatMagique = degatMagique; _degatPhysique = degatPhysique; } } } <file_sep>namespace RPG.Core.Items { class Item { protected string _nom; protected string _description; public string Nom { get { return _nom; } } public string Description { get { return _description; } } protected Item(string nom, string description) { _nom = nom; _description = description; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPG.Core { class Entity { protected int _pvMax; protected int _pvActuel; protected int _manaMax; protected int _manaActuel; protected int _force; protected int _intel; protected int _armure; protected string _nom; protected int _level; public int PvMax { get { return _pvMax; } } public int PvActuel { get { return _pvActuel; } } public int ManaMax { get { return _manaMax; } } public int ManaActuel { get { return _manaActuel; } } public int Force { get { return _force; } } public int Intel { get { return _intel; } } public int Armure { get { return _armure; } } public string Nom { get { return _nom; } } public int Level { get { return _level; } } public Entity(int pvMax,int manaMax,int force,int intel,int armure,string nom,int level) { _pvMax = pvMax; _pvActuel = pvMax; _manaMax = manaMax; _manaActuel = manaMax; _force = force; _intel = intel; _armure = armure; _nom = nom; _level = level; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPG.Core { interface ISoignable { void Soigner(int PvGagner; } }
2ecf867758c0961e4210844b28619795a4a585f4
[ "C#" ]
8
C#
Sakyo59/RPG
57b2799bcd4d87c70e3548b072659f33c3f77f29
60c4c15a8df2a2062a0cc157eab50d732d2961eb
refs/heads/master
<repo_name>wshenk/pcapmap<file_sep>/README.md # pcapmap **pcapmap** utilizes Scapy to quickly parse pcap files for active hosts and ports. ### Usage: ``` python3 pcapmap.py [-h] [-n] [-t TIMEOUT] pcap_file Parse pcap file for hosts, protocols, and ports positional arguments: pcap_file optional arguments: -h, --help show this help message and exit -n, --no-dns-resolve Do not resolve hostnames from IP Addresses (default: resolve hostnames) -t TIMEOUT, --timeout TIMEOUT Timeout in seconds (default: 20) ``` ### Dependencies: * python3 * scapy * twisted ``` pip3 install -r requirements.txt ``` ### Examples: ##### HTTP Request Example ``` python3 pcapmap.py http.cap [+][0] New Host Found! IP Addr: 192.168.127.12 [+][0] New Host Found! IP Addr: 172.16.58.3 [+][12] New Host Found! IP Addr: 172.16.31.10 [+][17] New Host Found! IP Addr: 172.16.58.3 [+] Reverse Name Resolution Complete! IP Addr: 192.168.127.12 Hostname: dialin-145-254-160-237.pools.arcor-ip.net [-] Reverse Name Resolution Failed! IP Addr: 172.16.58.3 [-] Reverse Name Resolution Failed! IP Addr: 172.16.31.10 [-] Reverse Name Resolution Failed! IP Addr: 172.16.58.3 ******************* * PCAPMAP Results * ******************* -------------------------- Ip Addr: 172.16.31.10 Current Hostname: Unknown Status at Capture Time: UP (Packets observed originating from host) Ports: 53/udp -------------------------- Ip Addr: 192.168.127.12 Current Hostname: dialin-145-254-160-237.pools.arcor-ip.net Status at Capture Time: UP (Packets observed originating from host) Ports: 3371/tcp 3372/tcp 3009/udp -------------------------- Ip Addr: 172.16.58.3 Current Hostname: Unknown Status at Capture Time: UP (Packets observed originating from host) Ports: 80/tcp -------------------------- Ip Addr: 172.16.58.3 Current Hostname: Unknown Status at Capture Time: UP (Packets observed originating from host) Ports: 80/tcp LISTENING (SYNACK verified) -------------------------- ``` ##### Slammer Worm Example ``` python3 pcapmap.py slammer.pcap [+][0] New Host Found! IP Addr: 172.16.17.32 [+][0] New Host Found! IP Addr: 192.168.3.11 [+] Reverse Name Resolution Complete! IP Addr: 172.16.17.32 Hostname: 22.212.76.213.dynamic.jazztel.es [+] Reverse Name Resolution Complete! IP Addr: 192.168.3.11 Hostname: 65-165-167-86.volcano.net ******************* * PCAPMAP Results * ******************* -------------------------- Ip Addr: 172.16.17.32 Current Hostname: 22.212.76.213.dynamic.jazztel.es Status at Capture Time: UP (Packets observed originating from host) Ports: 20199/udp -------------------------- Ip Addr: 192.168.3.11 Current Hostname: 65-165-167-86.volcano.net Status at Capture Time: UNKNOWN (No packets observed originating from host) Ports: 1434/udp -------------------------- Elapsed Execution Time: 00:00:10.01 ``` <meta name="google-site-verification" content="<KEY>" /> <file_sep>/pcapmap.py #!/usr/bin/env python3 from scapy.layers.inet import IP, TCP, UDP from scapy.sendrecv import sniff from twisted.names import client from twisted.internet import reactor import argparse, time, sys FIN = 0x01 SYN = 0x02 RST = 0x04 PSH = 0x08 ACK = 0x10 URG = 0x20 ECE = 0x40 CWR = 0x80 ip_src = '' ip_dest = '' tcp_sport = 0 tcp_dport = 0 num_packets_parsed = 0 def parse_packet(host_list): def parse_packet_int(packet): global num_packets_parsed src_host = None src_socket = None dst_host = None dst_socket = None socket_connection = None if IP in packet: src_host = host_list.add_or_find_host(Host(packet[IP].src), Host.PORT_SRC) src_host.status = Host.STATUS_UP dst_host = host_list.add_or_find_host(Host(packet[IP].dst), Host.PORT_DST) if TCP in packet: src_socket = Socket(src_host.ip_addr, packet[TCP].sport, Socket.TRANS_TCP, Socket.STATUS_UP) dst_socket = Socket(dst_host.ip_addr, packet[TCP].dport, Socket.TRANS_TCP, Socket.STATUS_UNK) src_socket = src_host.add_or_find_socket(src_socket) dst_socket = dst_host.add_or_find_socket(dst_socket) flags = packet[TCP].flags if flags & SYN and flags & ACK: src_socket.stype = Socket.TYPE_SERVER elif flags & SYN and not flags & ACK: src_socket.stype = Socket.TYPE_CLIENT elif UDP in packet: src_socket = Socket(src_host.ip_addr, packet[UDP].sport, Socket.TRANS_UDP, Socket.STATUS_UP) dst_socket = Socket(dst_host.ip_addr, packet[UDP].dport, Socket.TRANS_UDP, Socket.STATUS_UNK) src_socket = src_host.add_or_find_socket(src_socket) dst_socket = dst_host.add_or_find_socket(dst_socket) if TCP in packet or UDP in packet: socket_connection = SocketConnection(src_socket, dst_socket) src_socket.add_or_find_socket_connection(socket_connection) dst_socket.add_or_find_socket_connection(socket_connection) num_packets_parsed += 1 return parse_packet_int class SocketConnection: def __init__(self, socket1, socket2): self.socket_set = set() self.socket_set.add(socket1) self.socket_set.add(socket2) self.socket1 = socket1 self.socket2 = socket2 def __hash__(self): hashstr = "" for socket in sorted(self.socket_set): hashstr += socket.ip_addr hashstr += str(socket.port) return hash(hashstr) class Socket: TRANS_UDP = 0 TRANS_TCP = 1 TRANS_STRINGS = [ "udp" , "tcp" ] TYPE_UNK = 0 TYPE_CLIENT = 1 TYPE_SERVER = 2 STATUS_UNK = 0 STATUS_UP = 1 def __init__(self, ip_addr, port, trans, status=STATUS_UNK, stype=TYPE_UNK): self.ip_addr = ip_addr self.port = port self.trans = trans self.status = status self.socket_connection_set = set() self.stype = stype def __hash__(self): return hash(str(self.port) + self.ip_addr) def __lt__(self, other): return self.ip_addr + str(self.port) < self.ip_addr + str(other.port) def __eq__(self, other): return self.ip_addr + str(self.port) == self.ip_addr + str(other.port) def __gt__(self, other): return self.ip_addr + str(self.port) > self.ip_addr + str(other.port) def add_or_find_socket_connection(self, socket_connection): identifying_socket = None if socket_connection.socket1 == self: identifying_socket = socket_connection.socket2 else: identifying_socket = socket_connection.socket1 for socket_conn in self.socket_connection_set: if identifying_socket in socket_conn.socket_set: return socket_conn self.socket_connection_set.add(socket_connection) return socket_connection def get_string_trans(self): return Socket.TRANS_STRINGS[self.trans] def set_type(self, stype): self.stype = stype class Host: STATUS_UNK = 0 STATUS_UP = 1 STATUS_STRINGS = ["UNKNOWN (No packets observed originating from host)", "UP (Packets observed originating from host)"] PORT_SRC = 0 PORT_DST = 1 HOST_SRC = 2 HOST_DST = 3 def __init__(self, ip_addr=''): self.ip_addr = ip_addr self.tcp_port_set = set() self.synack_port_set = set() self.udp_port_set = set() self.hostname = "Unknown" self.status = Host.STATUS_UNK self.packet_count = -1 self.socket_set = set() def resolve_name(self): #try: # self.hostname = socket.gethostbyaddr(self.ip_addr)[0] #except socket.herror: # self.hostname = "Unknown" self.d = client.lookupPointer(name=self.reverse_name_for_ip_address()) self.d.addCallback(self.lookup_ptr_callback) return self.d # if answers: # self.hostname = answers[0] def lookup_ptr_callback(self, result): answers, authority, additional = result if answers: return answers def dns_success(self, result): global num_packets_parsed recordHeader = result[0] name_str_list = str(recordHeader.payload).split(' ') for name_str in name_str_list: if "name=" in name_str: self.hostname = name_str.split('=')[1] print("[+] Reverse Name Resolution Complete! IP Addr: %s Hostname: %s" % (self.ip_addr, self.hostname)) def dns_error(self, failure): import sys sys.stderr.write("[-] Reverse Name Resolution Failed! IP Addr: %s\n" % self.ip_addr) def reverse_name_for_ip_address(self): return '.'.join(reversed(self.ip_addr.split('.'))) + '.in-addr.arpa' def __lt__(self, other): return self.ip_addr < other.ip_addr def __eq__(self, other): return self.ip_addr == other.ip_addr def __gt__(self, other): return self.ip_addr > other.ip_addr def __str__(self): return self.ip_addr def __hash__(self): return hash(self.ip_addr) def add_or_find_socket(self, socket): if socket not in self.socket_set: self.socket_set.add(socket) return socket else: for ret_socket in self.socket_set: if ret_socket == socket: return ret_socket def print_new(self, include_hostnames=False): print("Ip Addr: %s" % self.ip_addr) if include_hostnames == True: print("Current Hostname: %s" % self.hostname) print("Status at Capture Time: %s" % Host.STATUS_STRINGS[self.status]) print("Ports: ") for socket in sorted(self.socket_set): print(" %i/%s" % (socket.port, socket.get_string_trans()), end='') if socket.stype == Socket.TYPE_SERVER: print(" <-- LISTENING (SYNACK observed)") elif socket.stype == Socket.TYPE_CLIENT: print(" +-- CLIENT (SYN observed)") elif socket.stype == Socket.TYPE_UNK: print(" --- UNK") last_print_sock = None sock_counter = 0 num_socks = len(socket.socket_connection_set) for sock_conn in socket.socket_connection_set: print_sock = None if sock_conn.socket1 == socket: print_sock = sock_conn.socket2 else: print_sock = sock_conn.socket1 if sock_counter == 0: if socket.stype == Socket.TYPE_SERVER: print(" --+ %s :%i" %(print_sock.ip_addr, print_sock.port), end='') elif socket.stype == Socket.TYPE_CLIENT: print(" --> %s :%i" %(print_sock.ip_addr, print_sock.port), end='') elif socket.stype == Socket.TYPE_UNK: print(" --- %s :%i" %(print_sock.ip_addr, print_sock.port), end='') else: print(" :%i" % print_sock.port, end='') last_print_sock = print_sock sock_counter += 1 if num_socks == sock_counter: print("") print("") class HostList(): def __init__(self, host_set=set(), dns_resolve=False): self.host_set = host_set self.dns_resolve = dns_resolve def add_or_find_host(self, host, direction): global num_packets_parsed if host not in self.host_set: print("[+][%i] New Host Found! IP Addr: %s " %(num_packets_parsed, host.ip_addr)) if self.dns_resolve == True: d = host.resolve_name() d.addCallback(host.dns_success) d.addErrback(host.dns_error) if direction == Host.HOST_SRC: host.status = Host.STATUS_UP self.host_set.add(host) return host else: for ret_host in self.host_set: if ret_host == host: return ret_host def print(self): print("\n*******************\n* PCAPMAP Results *\n*******************") for host in sorted(self.host_set): print("\n--------------------------\n") host.print_new(self.dns_resolve) print("\n--------------------------") def main(argv): start = time.time() parser = argparse.ArgumentParser(description='Parse pcap file for hosts, protocols, and ports') parser.add_argument('pcap_file', nargs=1) parser.add_argument('-n', '--no-dns-resolve', required=False, action='store_true', help="Do not resolve hostnames from IP Addresses (default: resolve hostnames)") parser.add_argument('-t', '--timeout', required=False, default=20, help="Timeout in seconds (default: 20)") args = parser.parse_args(argv) pcap_file = args.pcap_file host_list = HostList(set(), not args.no_dns_resolve) packets = sniff(offline=pcap_file, prn=parse_packet(host_list), store=0) if args.no_dns_resolve == False: reactor.callLater(10, reactor.stop); reactor.run() host_list.print() end = time.time() hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, args.timeout) print("\nElapsed Execution Time: {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds)) if __name__ == "__main__": main(sys.argv[1:])
cb1ac0fc7c8101fc2ab54a3339e2c295a7fc36f8
[ "Markdown", "Python" ]
2
Markdown
wshenk/pcapmap
f4d4788770cdabe3d0d7cc6d770dd27bb749242f
9199479d47fab0d23a163cb4faac387e37144957
refs/heads/main
<repo_name>AnadeLuna/streamlit_me_mola<file_sep>/src/manage_data.py import pandas as pd def renombra_id(x): x = f"Frase {x}" return x def carga_data(): data = pd.read_pickle("data/clean.pkl") return data def grafico_barras_st(): data = carga_data() data = data.groupby("character_name").agg({"character_name":'count'}).rename(columns={"character_name":"character_name", "character_name":"número de frases"}).reset_index().set_index("character_name", drop=True) return data def lista_personajes(): data = carga_data() return list(data.character_name.unique()) def grafico(personaje): data = carga_data() data = data[(data["character_name"] == f"{personaje}")] data = data[["frase","polarity"]].reset_index(drop=True) data["frase"] = data.index+1 data["frase"] = data.frase.apply(renombra_id) return data def bar_2(): data= carga_data() data = data.groupby("character_name").agg({"polarity":"mean"}).reset_index().set_index("character_name", drop=True) return data<file_sep>/main.py import streamlit as st import src.manage_data as dat import plotly.express as px import pandas as pd import folium import codecs from streamlit_folium import folium_static import streamlit.components.v1 as components from PIL import Image imagen = Image.open("images/portada2.jpg") st.image(imagen) st.write(""" # My awesome app Con Jake el perro y Finn el humano lo pasaremos guaaaaaaaay """ ) st.dataframe(dat.carga_data()) st.write(""" ### Grafiquito de Barras propio de streamlit """ ) datos_grafico = dat.grafico_barras_st() st.dataframe(datos_grafico) st.bar_chart(datos_grafico) st.write(""" ### Grafiquito de Plotly """) person = st.selectbox( "Selecciona un personaje", dat.lista_personajes() ) datagraf = dat.grafico(person) fig = px.line(datagraf, y="polarity", title = f"Evolución de la polaridad de {person}", labels = {"index": "Frases"} ) st.plotly_chart(fig) st.write(""" ### Gestor de archivos """) uploaded_file = st.file_uploader("Sube un csv") if uploaded_file is not None: dataframe = pd.read_csv(uploaded_file) st.write(dataframe) st.write(""" ### Columnas """) datos = dat.bar_2() col1,col2 = st.beta_columns([4,2]) col1.subheader("El gráfico") col1.bar_chart(datos) col2.subheader("Los datitos") col2.write(datos) st.write(""" ### Mapita de Folium """) map_1 = folium.Map(location = [40.4143851,-3.6820241], zoom_start = 15) folium_static (map_1) st.write(""" ### Mapita insertado con HTML """) archivo = codecs.open("data/mapa.html",'r') mapa = archivo.read() components.html(mapa, height = 550)<file_sep>/requirements.txt streamlit_folium==0.2.0 pandas folium==0.12.1 streamlit==0.77.0 Pillow==8.1.2 plotly==4.14.3
181715a18b64527d4004b7cf95a9b7e92c879cfb
[ "Python", "Text" ]
3
Python
AnadeLuna/streamlit_me_mola
83bae101dfb7f4c9bbe6639ac2824ccfff176980
89a0703a28946ed0ae797c8abc3fd3b68785c339
refs/heads/master
<file_sep>package com.exercise.pokerhand; /** * Card class is used to represent a single card in the hand. * There will only be one instance of each card type. * * @author <NAME> * */ public class Card implements Comparable<Object> { private String suit; private String value; private int rank; /** * Default constructor to initialize a card. * * @param suit * @param value * @param rank */ public Card(String suit, String value, int rank) { super(); this.suit = suit; this.rank = rank; this.value = value; } /** * Method to compare two cards based on their ranks. Returns 0 when equal, * -1 when less, 1 when greater. * */ public int compareTo(Object object) { if (this.rank == ((Card) object).rank) return 0; else if (this.rank < ((Card) object).rank) return -1; else return 1; } /** * Helper method to display card's value and suit. * */ public void displayCard() { System.out.print(value + suit + " "); } /** * Returns the rank of the card. * * @return rank */ public int getRank() { return rank; } /** * Returns the suit of the card. * * @return suit */ public String getSuit() { return suit; } /** * Returns the value of the card. * * @return */ public String getValue() { return value; } /** * Set the rank of the card. * * @param rank */ public void setRank(int rank) { this.rank = rank; } /** * Set the suit of the card. * * @param suit */ public void setSuit(String suit) { this.suit = suit; } /** * Set the value of the card. * * @param value */ public void setValue(String value) { this.value = value; } } <file_sep>package com.exercise.pokerhand; /** * Constants Class is used to store all the string and number constant values * used during hand evaluation as well as for display. * * @author US * */ public class Constants { // public static String handRanks[] = { "Royal Flush", "Straight Flush", // "Four of a Kid", "Full House", "Flush", "Straight", // "Three of a kind", "Two pair", "One pair", "High Card" }; public static String suitsName[] = { "clubs", "diamonds", "hearts", "spades" }; public static String suits[] = { "c", "d", "h", "s" }; public static String values[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "K", "Q", "J" }; public static int ranks[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; public static String spadesFlushFormat = "s,s,s,s,s"; public static String clubsFlushFormat = "c,c,c,c,c"; public static String heartsFlushFormat = "h,h,h,h,h"; public static String diamondsFlushFormat = "d,d,d,d,d"; }
153d8960b71529edc7c73a737e3f230ed648e441
[ "Java" ]
2
Java
raodeepa/Poker
0d19a5865819f722946564c8538e446b8f1676e1
86e699a8a830097daf7a639c50bd7d18c0cd234e
refs/heads/master
<repo_name>awesomephant/humboldt-theme<file_sep>/static/site.js var gri = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } const randomiseCards = function () { var objectImages = document.querySelectorAll('.object-list .card'); for (var i = 0; i < objectImages.length; i++) { let obj = objectImages[i]; obj.style.maxWidth = gri(70, 100) + '%'; } } document.addEventListener("DOMContentLoaded", function () { var objects = "{{objects|join(',')}}"; objects = objects.split(',') var searchField = document.querySelector('.search-field'); searchField.setAttribute('placeholder', 'Suche "' + objects[gri(0, objects.length)] + '"') console.log(objects); // Handler when the DOM is fully loaded randomiseCards(); }); <file_sep>/single.php <?php /** * The Template for displaying all single posts * * Methods for TimberHelper can be found in the /lib sub-directory * * @package WordPress * @subpackage Timber * @since Timber 0.1 */ $context = Timber::get_context(); $post = Timber::query_post(); $context['post'] = $post; $myClass = wp_get_post_terms($post->ID, 'bio_class')[0]->slug; $context['myClass'] = wp_get_post_terms($post->ID, 'bio_class')[0]; $args = array( 'post_type' => 'object', 'showposts' => 6, 'tax_query' => array( array( 'taxonomy' => 'bio_class', 'field' => 'slug', 'terms' => $myClass, ), ), ); $context['related_class'] = Timber::get_posts( $args ); if ( post_password_required( $post->ID ) ) { Timber::render( 'single-password.twig', $context ); } else { Timber::render( array( 'single-' . $post->ID . '.twig', 'single-' . $post->post_type . '.twig', 'single.twig' ), $context ); }
f8b230f64ac40503570666b0326ff7ddd6ef3f0b
[ "JavaScript", "PHP" ]
2
JavaScript
awesomephant/humboldt-theme
6e995353c0178b6981017236e3957f062dfe5c86
c9bfd0ee97b19e29c698191775391d31503ebefb
refs/heads/master
<repo_name>rock626/Particle_Filter<file_sep>/src/particle_filter.cpp /* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: <NAME> */ #define _USE_MATH_DEFINES #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). default_random_engine gen; double std_x, std_y, std_theta; // This line creates a normal (Gaussian) distribution for x with mean as given value normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); num_particles=100; for(int i=0;i<num_particles;i++){ Particle p; p.id =i; p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); p.weight = 1; particles.push_back(p); } // cout << "init done" << endl; is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ default_random_engine gen; // This line creates a normal (Gaussian) distribution for x, with mean as 0 normal_distribution<double> dist_x(0, std_pos[0]); normal_distribution<double> dist_y(0, std_pos[1]); normal_distribution<double> dist_theta(0, std_pos[2]); // cout << "Prediction" << endl; for(int i=0;i<num_particles;i++){ //add measurements to existing values double val1 = particles[i].theta + (yaw_rate * delta_t); if(yaw_rate == 0) { particles[i].x += (velocity * delta_t) * cos(particles[i].theta); particles[i].y += (velocity * delta_t) * sin(particles[i].theta); //particles[i].theta = particles[i].theta; } else { particles[i].x += (velocity/yaw_rate) * (sin(val1) - sin(particles[i].theta)); particles[i].y += (velocity/yaw_rate) * (cos(particles[i].theta) - cos(val1)); particles[i].theta += yaw_rate * delta_t; } //add noise particles[i].x += dist_x(gen); particles[i].y += dist_y(gen); particles[i].theta += dist_theta(gen); // cout << "Particle " << i << ": x:" <<particles[i].x << " y:" << particles[i].y << " theta:" << particles[i].theta << " weight:" << particles[i].weight << endl; } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. } double euclideanDistance(double x1, double y1, double x2, double y2) { double x = x1 - x2; double y = y1 - y2; double dist; dist = pow(x,2)+pow(y,2); //calculating distance by euclidean formula dist = sqrt(dist); //sqrt is function in math.h return dist; } Map::single_landmark_s nearestLandMark(double sensor_range,double x_map,double y_map, const Map &map_landmarks) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. double min = std::numeric_limits<double>::max(); // cout << "Initial min value" << min << endl; Map::single_landmark_s nearestLandMark; for(int i=0;i<map_landmarks.landmark_list.size();i++){ Map::single_landmark_s landmark = map_landmarks.landmark_list[i]; if(abs(landmark.x_f - x_map) <= sensor_range && abs(landmark.y_f - y_map) <= sensor_range){ //eculidean distance double distance = euclideanDistance(x_map,y_map,landmark.x_f,landmark.y_f); if(distance < min){ min = distance; nearestLandMark = landmark; } }else{ // cout << "out of range x_map:" << x_map << " y_map" << y_map << " landmark x:"<< landmark.x_f << " y:" << landmark.y_f <<endl; } } return nearestLandMark; } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html //clear weights vector; weights.clear(); //for each particle double x_map; double y_map; // cout << "Update weights" << endl; double gaussian_norm = 1/(2*M_PI * std_landmark[0] * std_landmark[1]); for(int i=0;i<num_particles;i++){ //for each observation // cout << "Particle " << i << ": x:" <<particles[i].x << " y:" << particles[i].y << " theta:" << particles[i].theta << endl; double particle_weight=1.0; std::vector<int> associations_new; std::vector<double> sense_x_new; std::vector<double> sense_y_new; std::vector<double> p_weights; for(int j=0;j<observations.size();j++){ LandmarkObs l_obs = observations[j]; // cout << "Observation id:"<< j << " x:" << l_obs.x << " y:" << l_obs.y << endl; x_map = particles[i].x + (cos(particles[i].theta) * l_obs.x) - (sin(particles[i].theta)*l_obs.y); y_map = particles[i].y + (sin(particles[i].theta) * l_obs.x) + (cos(particles[i].theta)*l_obs.y); // cout << "Mapping:"<< j << " x_map:" << x_map << " y_map:" << y_map << endl; Map::single_landmark_s mu = nearestLandMark(sensor_range,x_map,y_map,map_landmarks); // cout << "NearestLandMark " << mu.id_i << ": x:" <<mu.x_f << " y:" << mu.y_f << endl; //set associations and sense_x, sense_y associations_new.push_back(mu.id_i); sense_x_new.push_back(x_map); sense_y_new.push_back(y_map); //calculate weight double exp_x = pow((x_map - mu.x_f),2)/(2 * pow(std_landmark[0],2)); double exp_y = pow((y_map - mu.y_f),2)/(2 * pow(std_landmark[1],2)); double exponent = exp_x+exp_y; double weight = gaussian_norm * exp(-exponent); // cout << "gaussian_norm:"<< gaussian_norm <<" exp_x:" << exp_x << " exp_y:" << exp_y << " exponent:" << exponent << endl; // cout << "weight:" << weight << endl; //final weight is by multiplying all the calculated measurement probabilities together. p_weights.push_back(weight); } double c_weight =1.0; for(int k=0;k<p_weights.size();k++){ c_weight *= p_weights[k]; } // cout << "cumulative weight:" << c_weight << endl; SetAssociations(particles[i],associations_new,sense_x_new,sense_y_new); particles[i].weight = c_weight; weights.push_back(c_weight); cout << endl; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution std::random_device rd; std::mt19937 gen(rd()); std::discrete_distribution<double> distribution(weights.begin(),weights.end()); // cout << "Before resampling: " << endl; // for(int i=0;i<num_particles;i++){ // // cout << weights[i] << " " << endl; // } std::vector<Particle> p_new; // cout << "After resampling: " << endl; for(int i=0;i<num_particles;i++){ int index = distribution(gen); p_new.push_back(particles[index]); // cout << particles[index].weight << " " << endl; } particles = p_new; cout << endl; } Particle ParticleFilter::SetAssociations(Particle particle, std::vector<int> associations, std::vector<double> sense_x, std::vector<double> sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates //Clear the previous associations particle.associations.clear(); particle.sense_x.clear(); particle.sense_y.clear(); particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; return particle; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
3d895c650b1858a8bfb05131949824c11416af57
[ "C++" ]
1
C++
rock626/Particle_Filter
9f31029aee4eab455ed4299376f2b3d185327ca0
eb00cdec5a4b4e0fe45c49a8f881083f68d3783b
refs/heads/master
<repo_name>NDehkordi/SuperDuperUniv<file_sep>/src/java/besteman/model/StudentFinancial.java /* * 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. */ package besteman.model; /** * * @author besteman */ public class StudentFinancial { String student_number; private String creditcard; private String current_due; private String past_payment; public StudentFinancial() { this.student_number = student_number; this.creditcard = creditcard; this.current_due = current_due; this.past_payment = past_payment; } public String getStudent_number() { return student_number; } public void setStudent_number(String student_number) { this.student_number = student_number; } public String getCreditcard() { return creditcard; } public void setCreditcard(String creditcard) { this.creditcard = creditcard; } public String getCurrent_due() { return current_due; } public void setCurrent_due(String current_due) { this.current_due = current_due; } public String getPast_payment() { return past_payment; } public void setPast_payment(String past_payment) { this.past_payment = past_payment; } } <file_sep>/src/java/besteman/model/Course.java /* * 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. */ package besteman.model; import java.io.Serializable; /** * * @author <NAME> */ public class Course implements Serializable { private String courseDept; private String courseNumber; private String courseTitle; private String courseDayNTime; private String courseRoom; private String courseInstructor; private int courseCredit; private String courseCode; public Course(String courseCode, String courseDept, String courseNumber,String courseTitle,String courseDayNTime,String courseRoom, String courseInstructor, int courseCredit) { this.courseDept = courseDept; this.courseNumber = courseNumber; this.courseTitle = courseTitle; this.courseDayNTime = courseDayNTime; this.courseRoom = courseRoom; this.courseInstructor = courseInstructor; this.courseCredit = courseCredit; this.courseCode = courseCode; } public Course() { courseDept = ""; courseNumber = ""; courseTitle = ""; courseDayNTime = "TBA"; courseRoom = "TBA"; courseInstructor = "TBA"; courseCredit = 0; courseCode = ""; } public String getCourseDept() { return courseDept; } public void setCourseDept(String courseDept) { this.courseDept = courseDept; } public String getCourseNumber() { return courseNumber; } public void setCourseNumber(String courseNumber) { this.courseNumber = courseNumber; } public String getCourseTitle() { return courseTitle; } public void setCourseTitle(String courseTitle) { this.courseTitle = courseTitle; } public String getCourseDayNTime() { return courseDayNTime; } public void setCourseDayNTime(String courseDayNTime) { this.courseDayNTime = courseDayNTime; } public String getCourseRoom() { return courseRoom; } public void setCourseRoom(String courseRoom) { this.courseRoom = courseRoom; } public String getCourseInstructor() { return courseInstructor; } public void setCourseInstructor(String courseInstructor) { this.courseInstructor = courseInstructor; } public int getCourseCredit() { return courseCredit; } public void setCourseCredit(int courseCredit) { this.courseCredit = courseCredit; } public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } } <file_sep>/src/java/besteman/controller/SelectCourseServlet.java /* * 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. */ package besteman.controller; import besteman.model.Course; import besteman.model.database.DBCourse; import java.io.IOException; import java.io.PrintWriter; import static java.lang.System.out; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; /** * * @author <NAME> */ @WebServlet(name = "SelectCourseServlet", urlPatterns = {"/SelectCourseServlet"}) public class SelectCourseServlet extends HttpServlet { //array of objects used to hold database data ArrayList<Course> courseList = new ArrayList<Course>(); ArrayList<Course> coursesSelected = new ArrayList<Course>(); String url; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { url = "/view/index.jsp"; //String action = request.getParameter("action"); HttpSession session = request.getSession(); //session.setAttribute("courseList", courseList); // if (request.getParameter("homepage") != null) { courseList.clear(); ArrayList<Course> courseList = new ArrayList<Course>(); courseList = DBCourse.selectAllCourses(); // Course selectAllCourse = new Course(); // // for(int i = 0; i < courseList.size(); i++ ) // { // // selectAllCourse = DBCourse.selectAllCourses(); // courseList.add(i, new Course(selectAllCourse.getCourseCode(), selectAllCourse.getCourseDept(), selectAllCourse.getCourseNumber(), selectAllCourse.getCourseTitle(), // selectAllCourse.getCourseDayNTime(), selectAllCourse.getCourseRoom(), selectAllCourse.getCourseInstructor(), selectAllCourse.getCourseCredit())); // courseList.add(0, new Course("111111", "Art", "110", "Intro to Art", "MW, 2:00-3:00", "A256", "Bosch", 3)); // courseList.add(1, new Course("222221", "CIS", "110", "Intro to Programming", "TBD", "F115", "Turing", 3)); // courseList.add(2, new Course("333331", "ENG", "100", "Freshmen English", "TBD", "A130", "Forster-Wallace", 3)); // courseList.add(3, new Course("444441", "HIST", "110", "Intro to History", "TBD", "C253", "Pettibone", 3)); // } // // session.setAttribute("courseList", courseList); url = "/view/select_course.jsp"; // } if (request.getParameter("submit_courses") != null) { coursesSelected.clear(); for (int i = 0; i < courseList.size(); i++) { if (request.getParameter("check" + i) != null) { coursesSelected.add(courseList.get(i)); } } session.setAttribute("coursesSelected", coursesSelected); url = "/view/select_course_results.jsp"; } else if (request.getParameter("go_home") != null) { url = "/view/index.jsp"; } else { url = "/view/select_course.jsp"; } getServletContext().getRequestDispatcher(url).forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(SelectCourseServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(SelectCourseServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/src/java/besteman/model/StudentAcademic.java /* * 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. */ package besteman.model; /** * * @author besteman */ public class StudentAcademic { private String student_number; private String[] courses_taken; private String[] current_courses; private int credits; public StudentAcademic() { this.student_number = student_number; this.courses_taken = courses_taken; this.current_courses = current_courses; this.credits = credits; } public String getStudent_number() { return student_number; } public void setStudent_number(String student_number) { this.student_number = student_number; } public String[] getCourses_taken() { return courses_taken; } public void setCourses_taken(String[] courses_taken) { this.courses_taken = courses_taken; } public String[] getCurrent_courses() { return current_courses; } public void setCurrent_courses(String[] current_courses) { this.current_courses = current_courses; } public int getCredits() { return credits; } public void setCredits(int credits) { this.credits = credits; } } <file_sep>/src/java/besteman/model/database/DBAcademicRecord.java /* * 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. */ package besteman.model.database; import besteman.model.AcademicRecord; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author freddybeste */ public class DBAcademicRecord { public static double getGPA(String studentNumber) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT grade FROM academic_records WHERE student_number = ?"; try { double GPA = 0.0; int counter = 0; double points = 0; String grade; ps = connection.prepareStatement(query); ps.setString(1, studentNumber); rs = ps.executeQuery(); AcademicRecord record = null; if(rs != null) { while(rs.next()) { if(rs.getString("grade").equals("A") ) { points = points + 4; } else if(rs.getString("grade").equals("B")) { points = points + 3; } else if(rs.getString("grade").equals("C")) { points = points + 2; } else if (rs.getString("grade").equals("D")) { points = points + 1; } counter++; } GPA = points / counter; } return GPA; }catch (SQLException e) { System.out.println(e); return 0; } finally{ DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int getTotalCredits(String studentNumber) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT credits FROM academic_records WHERE student_number = ?"; try { int totalCredits = 0; ps = connection.prepareStatement(query); ps.setString(1, studentNumber); rs = ps.executeQuery(); AcademicRecord record = null; while(rs.next()) { totalCredits += rs.getInt("credits"); } return totalCredits; }catch (SQLException e) { System.out.println(e); return 0; } finally{ DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<AcademicRecord> selectRecord(String studentNumber) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT * FROM academic_records WHERE student_number = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, studentNumber); rs = ps.executeQuery(); ArrayList<AcademicRecord> academicRecord = new ArrayList<>(); AcademicRecord record = null; while(rs.next()) { academicRecord.add(new AcademicRecord(rs.getString("student_number"), rs.getString("course_title"), rs.getString("instructor"), rs.getString("days_and_time"), rs.getString("term"), rs.getInt("credits"), rs.getString("grade"))); } return academicRecord; }catch (SQLException e) { System.out.println(e); return null; } finally{ DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } } <file_sep>/src/java/besteman/model/Faculty.java /* * 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. */ package besteman.model; import java.io.Serializable; /** * * @author freddybeste */ public class Faculty implements Serializable { private String faculty_name; private String dept; private String p_word; public Faculty(String faculty_name, String dept, String p_word) { this.faculty_name = faculty_name; this.dept = dept; this.p_word = p_word; } public Faculty() { } public String getFaculty_name() { return faculty_name; } public void setFaculty_name(String faculty_name) { this.faculty_name = faculty_name; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getP_word() { return p_word; } public void setP_word(String p_word) { this.p_word = p_word; } }
40a1ab8dd638be4f42470c840391711d57efa861
[ "Java" ]
6
Java
NDehkordi/SuperDuperUniv
dcc23fa5d498e2e6d53649ee0513153f05737533
63e8d3ce9c04783db488591226f217d0a85cbd6c
refs/heads/main
<repo_name>AMAN123956/Working-with-Sessions-and-Cookies<file_sep>/src/routes/generalRoutes.js const router = require("express").Router(); const {landingController} = require('../controllers/general/landing') router.get('/', landingController) /* Exporting Router */ module.exports = router
c39047c09e75d749c47a068ca3c7a84b8ce42df3
[ "JavaScript" ]
1
JavaScript
AMAN123956/Working-with-Sessions-and-Cookies
2237283fac330e171d4f0d066dd481e12a5ea9bc
04f705a85cc36e00da4ec5c548041ef8de6e10d2
refs/heads/main
<repo_name>Drawserqzez/SpotifyCLI<file_sep>/src/Core/App.cs using Draws.CLI; using SpotifyAPI.Web; using SpotifyCLI.Services; using SpotifyCLI.Utilities; using System.Linq; using System.Threading.Tasks; namespace SpotifyCLI { public class App { private readonly IOutputHandler _outputHandler; private readonly CommandParser _parser; public App (CommandParser parser, IOutputHandler outputHandler) { _outputHandler = outputHandler; _parser = parser; } public void Run(string[] args) { _parser.Parse(args); } } }<file_sep>/src/Commands/SearchCommand.cs using Draws.CLI; using SpotifyAPI.Web; using System.Collections.Generic; using System.Linq; namespace SpotifyCLI.Commands { [Command("search", "Searches for a specified query etc")] [Argument("query", "The query to search with", false, true, 'q')] [Argument("track", "Searches for only tracks", true, false)] public class SearchCommand : ICommand { private Dictionary<string, string> _arguments; private readonly ISpotifyClient _spotify; public SearchCommand(ISpotifyClient spotify) { _spotify = spotify; } public string RunCommand() { string query = _arguments.FirstOrDefault(x => x.Key == "query").Value; SearchRequest.Types types = SearchRequest.Types.All; if (_arguments.ContainsKey("track")) { types = SearchRequest.Types.Track; } SearchRequest request = new SearchRequest(types, query); var res = _spotify.Search.Item(request).Result; string trackNames = ""; foreach (var track in res.Tracks.Items) { trackNames += $"{track.Name}\n"; } return trackNames; } public void SetArguments(Dictionary<string, string> args) { _arguments = args; } } }<file_sep>/src/Util/AppConfig.cs using Draws.CLI; using SpotifyAPI.Web; using System; using System.IO; using System.Reflection; using System.Text.Json; using System.Threading.Tasks; namespace SpotifyCLI.Utilities { public class AppConfig : IAppConfig { private readonly string _clientId; private string _directoryPath; private string _filePath; private readonly IOutputHandler _outputHandler; private PKCETokenResponse _tokens; public string ClientId { get { return _clientId; }} public PKCETokenResponse Tokens { get { return _tokens; }} public AppConfig(IOutputHandler outputHandler) { string location = AppDomain.CurrentDomain.BaseDirectory; _directoryPath = $"{location}/.config/"; _filePath = $"{location}/.config/appConfig.json"; _outputHandler = outputHandler; Configuration configData = Initialise(); _clientId = configData.ClientId; _tokens = configData.Tokens; } private Configuration GetConfiguration() { using StreamReader sr = new StreamReader(_filePath); var jsonData = sr.ReadToEnd(); sr.Close(); return JsonSerializer.Deserialize<Configuration>(jsonData, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } private Configuration Initialise() { var directoryInfo = new DirectoryInfo(_directoryPath); if (!directoryInfo.Exists) { directoryInfo.Create(); directoryInfo.Attributes = FileAttributes.Directory; } var configFile = new FileInfo(_filePath); if (!configFile.Exists) { _outputHandler.Output("No config file was found. Creating..."); var fileStream = configFile.Create(); fileStream.Close(); // TODO: Use future input-handler to take a client id from the user var configData = new Configuration() { ClientId = "ClientId123", Tokens = new PKCETokenResponse() { AccessToken = "" }}; string jsonData = JsonSerializer.Serialize<Configuration>(configData); File.WriteAllLines(_filePath, new string[] { jsonData }); // TODO: Remove this when the input logic is available _outputHandler.Output("The file has been created. Please replace the current client-id with one of your own."); _outputHandler.Output("You can get a client id from the spotify developer site."); } return GetConfiguration(); } public async Task SaveTokens(PKCETokenResponse tokenReponse) { _tokens = tokenReponse; Configuration configuration = GetConfiguration(); configuration.Tokens = tokenReponse; string jsonData = JsonSerializer.Serialize<Configuration>(configuration); await File.WriteAllLinesAsync(_filePath, new[] { jsonData } ); } } }<file_sep>/src/Commands/ChangeVolumeCommand.cs using Draws.CLI; using SpotifyAPI.Web; using System; using System.Collections.Generic; namespace SpotifyCLI.Commands { [Command("vol", "Changes the volume.", isSingleArgument: false)] [Argument("volume", "The number to set the volume to", required: true, shortName: 'v')] public class ChangeVolumeCommand : ICommand { private readonly ISpotifyClient _spotify; private int _newVolume; public ChangeVolumeCommand(ISpotifyClient spotifyClient) { _spotify = spotifyClient; } public string RunCommand() { _spotify.Player.SetVolume(new PlayerVolumeRequest(_newVolume)); return $"Set the volume to {_newVolume}%"; } public void SetArguments(Dictionary<string, string> args) { string newVolumeString = ""; args.TryGetValue("volume", out newVolumeString); _newVolume = Convert.ToInt32(newVolumeString); } } }<file_sep>/src/Services/AuthService.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Draws.CLI; using SpotifyAPI.Web; using SpotifyCLI.Utilities; namespace SpotifyCLI.Services { public class AuthService : IAuthService { private readonly string _challenge; private readonly IAppConfig _config; private readonly OAuthClient _oAuthClient; private readonly Uri _loginRequestUri; private readonly IOutputHandler _outputHandler; private const string _redirectUri = "http://localhost:1337/callback/"; private readonly string _verifier; public AuthService(IAppConfig config, IOutputHandler outputHandler, OAuthClient oAuthClient) { (_verifier, _challenge) = PKCEUtil.GenerateCodes(); _config = config; _outputHandler = outputHandler; var loginRequest = new LoginRequest(new Uri(_redirectUri), _config.ClientId, LoginRequest.ResponseType.Code) { CodeChallengeMethod = "S256", CodeChallenge = _challenge, Scope = new [] { Scopes.AppRemoteControl, Scopes.PlaylistModifyPrivate, Scopes.PlaylistModifyPublic, Scopes.PlaylistReadCollaborative, Scopes.PlaylistReadPrivate, Scopes.Streaming, Scopes.UserFollowModify, Scopes.UserFollowRead, Scopes.UserLibraryModify, Scopes.UserLibraryRead, Scopes.UserModifyPlaybackState, Scopes.UserReadCurrentlyPlaying, Scopes.UserReadPlaybackPosition, Scopes.UserReadPlaybackState, Scopes.UserReadPrivate, Scopes.UserReadRecentlyPlayed, Scopes.UserTopRead, } }; _oAuthClient = oAuthClient; _loginRequestUri = loginRequest.ToUri(); } private async Task<PKCETokenResponse> GetCallbackTokens(string code) { var initialResponse = await _oAuthClient.RequestToken(new PKCETokenRequest(_config.ClientId, code, new Uri(_redirectUri), _verifier)); _outputHandler.Output("Exchanged code for tokens."); return initialResponse; } public async Task<ISpotifyClient> CreateSpotifyClientAsync() { PKCETokenResponse tokenResponse = _config.Tokens; if (String.IsNullOrEmpty(tokenResponse.AccessToken) || String.IsNullOrEmpty(tokenResponse.RefreshToken)) tokenResponse = await UseNewTokens(); else if (tokenResponse.HasExpired()) tokenResponse = await RefreshTokens(); var config = SpotifyClientConfig.CreateDefault().WithAuthenticator(new PKCEAuthenticator(_config.ClientId, tokenResponse)); return new SpotifyClient(config); } private async Task<PKCETokenResponse> UseNewTokens() { _outputHandler.Output("Please authorize the app in the browser-window."); Process.Start(new ProcessStartInfo(_loginRequestUri.ToString()) { UseShellExecute = true }); string authCode = ""; using (var server = new HttpListener()) { server.Prefixes.Add(_redirectUri); _outputHandler.Output("Waiting for response from browser..."); server.Start(); while (server.IsListening) { var ctx = await server.GetContextAsync(); var request = ctx.Request; var response = request.QueryString; if (response.Get("error") != null) throw new AccessViolationException("Authorization failed"); authCode = response.Get("code"); _outputHandler.Output("Recieved code from callback."); server.Stop(); } } if (String.IsNullOrEmpty(authCode)) throw new Exception("Something went wrong while fetching the code"); var tokenResponse = await GetCallbackTokens(authCode); await _config.SaveTokens(tokenResponse); return tokenResponse; } private async Task <PKCETokenResponse> RefreshTokens() { try { _outputHandler.Output("Refreshing access-tokens, please wait a moment..."); var request = new PKCETokenRefreshRequest(_config.ClientId, _config.Tokens.RefreshToken); var res = await _oAuthClient.RequestToken(request); await _config.SaveTokens(res); return _config.Tokens; } catch (Exception e) { _outputHandler.Output("Something went wrong while trying to refresh the authentication token: "); _outputHandler.Output(e.Message); return await UseNewTokens(); } } } }<file_sep>/src/Commands/NextCommand.cs using Draws.CLI; using SpotifyAPI.Web; using System.Collections.Generic; namespace SpotifyCLI.Commands { [Command("next", "Skips forward to the next track", isSingleArgument: true)] public class NextCommand : ICommand { private ISpotifyClient _spotify; public NextCommand(ISpotifyClient spotifyClient) { _spotify = spotifyClient; } public string RunCommand() { _spotify.Player.SkipNext(); return $"Skipped forward"; } public void SetArguments(Dictionary<string, string> args) { } } }<file_sep>/src/Commands/PlayCommand.cs using System.Collections.Generic; using Draws.CLI; using SpotifyAPI.Web; namespace SpotifyCLI.Commands { [Command("play", "Sets the current player-status to play.", isSingleArgument: true)] public class PlayCommand : ICommand { private ISpotifyClient _spotify; public PlayCommand(ISpotifyClient spotifyClient) { _spotify = spotifyClient; } public string RunCommand() { bool isSuccess = _spotify.Player.ResumePlayback().Result; return (isSuccess) ? "Playback resumed" : "Could not set status."; } public void SetArguments(Dictionary<string, string> args) { } } }<file_sep>/src/Util/PKCETokenRefreshRequestExtensions.cs using System.Collections.Generic; using System.Net.Http; using SpotifyAPI.Web; namespace SpotifyCLI.Utilities { public static class PKCETokenRefreshRequestExtensions { public static FormUrlEncodedContent ToUrlEncoded(this PKCETokenRefreshRequest refreshRequest) { List<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>(); headers.Add(new KeyValuePair<string, string>("grant_type", "refresh_token")); headers.Add(new KeyValuePair<string, string>("refresh_token", refreshRequest.RefreshToken)); headers.Add(new KeyValuePair<string, string>("client_id", refreshRequest.ClientId)); return new FormUrlEncodedContent(headers); } } }<file_sep>/src/Services/Interfaces/IAuthService.cs using System.Threading.Tasks; using SpotifyAPI.Web; namespace SpotifyCLI.Services { public interface IAuthService { Task<ISpotifyClient> CreateSpotifyClientAsync(); } }<file_sep>/src/Commands/PauseCommand.cs using System.Collections.Generic; using Draws.CLI; using SpotifyAPI.Web; namespace SpotifyCLI.Commands { [Command("pause", "Sets the playback-status to pause.", isSingleArgument: true)] public class PauseCommand : ICommand { private readonly ISpotifyClient _spotify; public PauseCommand(ISpotifyClient spotifyClient) { _spotify = spotifyClient; } public string RunCommand() { bool isSuccess = _spotify.Player.PausePlayback().Result; return (isSuccess) ? "Playback paused" : "Could not pause playback"; } public void SetArguments(Dictionary<string, string> args) { } } } <file_sep>/src/Commands/ChangePlayStatusCommand.cs using Draws.CLI; using SpotifyAPI.Web; using System.Collections.Generic; using System.Threading.Tasks; namespace SpotifyCLI.Commands { [Command("playback", "Toggles the current player between play and pause", isSingleArgument: true)] public class ChangePlayStatusCommand : ICommand { private readonly ISpotifyClient _spotifyClient; private CurrentlyPlayingContext _currentlyPlaying; public ChangePlayStatusCommand(ISpotifyClient spotifyClient) { _spotifyClient = spotifyClient; GetCurrentlyPlaying().Wait(); } private async Task GetCurrentlyPlaying() { _currentlyPlaying = await _spotifyClient.Player.GetCurrentPlayback(); } public string RunCommand() { if (_currentlyPlaying.IsPlaying) _spotifyClient.Player.PausePlayback().Wait(); else if (!_currentlyPlaying.IsPlaying) _spotifyClient.Player.ResumePlayback().Wait(); return (_currentlyPlaying.IsPlaying) ? "Paused" : "Playing"; } // This command requires no arguments, so this is unused public void SetArguments(Dictionary<string, string> args) { // throw new System.NotImplementedException(); } } }<file_sep>/src/Commands/PreviousCommand.cs using System.Collections.Generic; using Draws.CLI; using SpotifyAPI.Web; namespace SpotifyCLI.Commands { [Command("back", "Skips to the previous track", isSingleArgument: true)] public class PreviousCommand : ICommand { private readonly ISpotifyClient _spotify; public PreviousCommand(ISpotifyClient spotifyClient) { _spotify = spotifyClient; } public string RunCommand() { _spotify.Player.SkipPrevious(); return "Skipped to previous track"; } public void SetArguments(Dictionary<string, string> args) { } } }<file_sep>/README.md # Spotify CLI This is a small hobby-project that makes a CLI for Spotify, written in C#. The goal of the project is to make as good of a Spotify experience as possible from the terminal, becaue I thought it'd be fun/useful to control spotify from there :D ## Setup 0. Clone or fork this repository 1. Add github-packages to your nuget-sources, because a dependency of this project is [my CLI library](https://github.com/Drawserqzez/CLI/) 2. Start coding :) ## Feature suggestions If there's a feature you'd like to see, please create an issue for it and I'll look it over :) Alternatively, you could try to make it yourself and create a pr :D ## Publishing and running the app 0. Open your terminal of choice and run the following command: > Please note that the project is by default configured for use with win-x64 ` dotnet publish -o <output-directory> -r <your-system> ` 2. Put the published contents in your PATH if you haven't already ## Todo - [ ] Make more commands - [x] Make a template for the config-file - [x] If no config file is found, guide the user to create one ## SpotifyAPI-NET This program uses a library [SpotifyAPI-NET](https://github.com/JohnnyCrazy/SpotifyAPI-NET) by <NAME> provided under the MIT license. ``` Copyright 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ```<file_sep>/Tests/ExtensionTests.cs using System; using FakeItEasy; using FluentAssertions; using SpotifyAPI.Web; using SpotifyCLI.Utilities; using Xunit; namespace SpotifyCLI.Tests { public class ExtensionTests { [Fact] public void Token_expiration_should_be_correct() { // Arrange var sut = new PKCETokenResponse(); sut.CreatedAt = DateTime.UtcNow.AddDays(-14); sut.ExpiresIn = 1; // Act var result = sut.HasExpired(); // Assert result.Should().BeTrue(); } } }<file_sep>/src/Util/ServiceCollectionExtensions.cs using Draws.CLI; using Microsoft.Extensions.DependencyInjection; using SpotifyAPI.Web; using SpotifyCLI.Commands; using SpotifyCLI.Services; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SpotifyCLI.Utilities { public static class ServiceCollectionExtensions { public static void AddSpotifyClient(this IServiceCollection services) { services.AddSingleton<ISpotifyClient>(_ => CreateSpotifyClient(_).Result); services.AddScoped<OAuthClient>(); } public static void AddSpotifyCLICommands(this IServiceCollection services) { services.AddTransient<IEnumerable<ICommand>>(_ => GetCommands(_)); } private static async Task<ISpotifyClient> CreateSpotifyClient(IServiceProvider serviceProvider) { var authService = serviceProvider.GetRequiredService<IAuthService>(); var client = await authService.CreateSpotifyClientAsync(); return client; } private static IEnumerable<ICommand> GetCommands(IServiceProvider serviceProvider) { List<ICommand> commands = new List<ICommand>(); var spotifyClient = (ISpotifyClient)serviceProvider.GetService<ISpotifyClient>(); commands.Add(new ChangePlayStatusCommand(spotifyClient)); commands.Add(new NextCommand(spotifyClient)); commands.Add(new PreviousCommand(spotifyClient)); commands.Add(new PlayCommand(spotifyClient)); commands.Add(new PauseCommand(spotifyClient)); commands.Add(new ChangeVolumeCommand(spotifyClient)); return commands; } } }<file_sep>/src/Util/Interfaces/IAppConfig.cs using SpotifyAPI.Web; using System.IO; using System.Threading.Tasks; namespace SpotifyCLI.Utilities { public interface IAppConfig { string ClientId { get; } PKCETokenResponse Tokens { get; } Task SaveTokens(PKCETokenResponse tokenResponse); } }<file_sep>/src/Program.cs using Draws.CLI; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SpotifyCLI.Services; using SpotifyCLI.Utilities; using System.Net.Http; namespace SpotifyCLI { class Program { static void Main(string[] args) { var host = Host.CreateDefaultBuilder() .ConfigureServices((Context, services) => { services.AddSingleton<HttpClient>(); services.AddScoped<App>(); services.AddScoped<IAuthService, AuthService>(); services.AddScoped<CommandParser>(); services.AddSingleton<IAppConfig, AppConfig>(); services.AddSingleton<IOutputHandler, CommandOutputHandler>(); services.AddSpotifyClient(); services.AddSpotifyCLICommands(); }) .Build(); var app = ActivatorUtilities.CreateInstance<App>(host.Services); app.Run(args); } } }<file_sep>/src/Util/PKCETokenResponseExtensions.cs using System; using SpotifyAPI.Web; namespace SpotifyCLI.Utilities { public static class PKCETokenResponseExtensions { public static bool HasExpired(this PKCETokenResponse token) { var created = token.CreatedAt; var expirationTime = token.ExpiresIn; return created.AddSeconds(expirationTime) < DateTime.UtcNow; } } }<file_sep>/Tests/CommandTests.cs using SpotifyCLI.Commands; using FluentAssertions; using FakeItEasy; using System; using Xunit; using SpotifyAPI.Web; using System.Collections.Generic; namespace SpotifyCLI.Tests { public class CommandTests { [Fact] public void Change_play_status_should_attempt_to_change_playback_status() { // Arrange var playingClient = A.Fake<ISpotifyClient>(); var pausedClient = A.Fake<ISpotifyClient>(); A.CallTo(() => playingClient.Player.GetCurrentPlayback()).Returns(new CurrentlyPlayingContext() { IsPlaying = true }); A.CallTo(() => pausedClient.Player.GetCurrentPlayback()).Returns(new CurrentlyPlayingContext() { IsPlaying = false }); var playingSut = new ChangePlayStatusCommand(playingClient); var pausedSut = new ChangePlayStatusCommand(pausedClient); // Act playingSut.RunCommand(); pausedSut.RunCommand(); // Assert A.CallTo(() => playingClient.Player.PausePlayback()).MustHaveHappenedOnceExactly(); A.CallTo(() => pausedClient.Player.ResumePlayback()).MustHaveHappenedOnceExactly(); } [Fact] public void Next_should_be_called_properly() { // Arrange var client = A.Fake<ISpotifyClient>(); A.CallTo(() => client.Player.SkipNext()).Returns(true); var sut = new NextCommand(client); // Act sut.RunCommand(); // Assert A.CallTo(() => client.Player.SkipNext()).MustHaveHappenedOnceExactly(); } [Fact] public void Previous_should_be_called_properly() { // Arrange var client = A.Fake<ISpotifyClient>(); A.CallTo(() => client.Player.SkipPrevious()).Returns(true); var sut = new PreviousCommand(client); // Act sut.RunCommand(); // Assert A.CallTo(() => client.Player.SkipPrevious()).MustHaveHappenedOnceExactly(); } } } <file_sep>/src/Util/Configuration.cs using SpotifyAPI.Web; namespace SpotifyCLI.Utilities { internal class Configuration { public string ClientId { get; set; } public PKCETokenResponse Tokens { get; set; } } }
60aec6698f1a2a774d6074b17e414eba326f0fd2
[ "Markdown", "C#" ]
20
C#
Drawserqzez/SpotifyCLI
dfed65334b89361be488876824632d7cb68cb3aa
545c8e22825affdec5fbfb6fdc11ca4350c3e0bc
refs/heads/main
<repo_name>maximeso/character-sheet<file_sep>/src/main/java/com/iledeslegendes/charactersheet/service/RaceService.java package com.iledeslegendes.charactersheet.service; import com.iledeslegendes.charactersheet.domain.Race; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * Service Interface for managing {@link Race}. */ public interface RaceService { /** * Save a race. * * @param race the entity to save. * @return the persisted entity. */ Race save(Race race); /** * Partially updates a race. * * @param race the entity to update partially. * @return the persisted entity. */ Optional<Race> partialUpdate(Race race); /** * Get all the races. * * @param pageable the pagination information. * @return the list of entities. */ Page<Race> findAll(Pageable pageable); /** * Get the "id" race. * * @param id the id of the entity. * @return the entity. */ Optional<Race> findOne(Long id); /** * Delete the "id" race. * * @param id the id of the entity. */ void delete(Long id); } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/service/impl/CharacterServiceImpl.java package com.iledeslegendes.charactersheet.service.impl; import com.iledeslegendes.charactersheet.domain.Character; import com.iledeslegendes.charactersheet.repository.CharacterRepository; import com.iledeslegendes.charactersheet.service.CharacterService; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing {@link Character}. */ @Service @Transactional public class CharacterServiceImpl implements CharacterService { private final Logger log = LoggerFactory.getLogger(CharacterServiceImpl.class); private final CharacterRepository characterRepository; public CharacterServiceImpl(CharacterRepository characterRepository) { this.characterRepository = characterRepository; } @Override public Character save(Character character) { log.debug("Request to save Character : {}", character); return characterRepository.save(character); } @Override public Optional<Character> partialUpdate(Character character) { log.debug("Request to partially update Character : {}", character); return characterRepository .findById(character.getId()) .map( existingCharacter -> { if (character.getName() != null) { existingCharacter.setName(character.getName()); } if (character.getAlignment() != null) { existingCharacter.setAlignment(character.getAlignment()); } if (character.getExperience() != null) { existingCharacter.setExperience(character.getExperience()); } if (character.getParty() != null) { existingCharacter.setParty(character.getParty()); } return existingCharacter; } ) .map(characterRepository::save); } @Override @Transactional(readOnly = true) public Page<Character> findAll(Pageable pageable) { log.debug("Request to get all Characters"); return characterRepository.findAll(pageable); } @Override @Transactional(readOnly = true) public Optional<Character> findOne(Long id) { log.debug("Request to get Character : {}", id); return characterRepository.findById(id); } @Override public void delete(Long id) { log.debug("Request to delete Character : {}", id); characterRepository.deleteById(id); } } <file_sep>/src/main/webapp/app/shared/model/skill.model.ts import { IRace } from 'app/shared/model/race.model'; import { ICareer } from 'app/shared/model/career.model'; export interface ISkill { id?: number; name?: string; cost?: number; restriction?: string; racialCondition?: IRace | null; careerCondition?: ICareer | null; skillCondition?: ISkill | null; } export const defaultValue: Readonly<ISkill> = {}; <file_sep>/src/main/webapp/app/shared/model/item.model.ts import { ICharacter } from 'app/shared/model/character.model'; export interface IItem { id?: number; reference?: string; name?: string; comment?: number; owner?: ICharacter | null; } export const defaultValue: Readonly<IItem> = {}; <file_sep>/src/main/java/com/iledeslegendes/charactersheet/service/impl/CareerServiceImpl.java package com.iledeslegendes.charactersheet.service.impl; import com.iledeslegendes.charactersheet.domain.Career; import com.iledeslegendes.charactersheet.repository.CareerRepository; import com.iledeslegendes.charactersheet.service.CareerService; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing {@link Career}. */ @Service @Transactional public class CareerServiceImpl implements CareerService { private final Logger log = LoggerFactory.getLogger(CareerServiceImpl.class); private final CareerRepository careerRepository; public CareerServiceImpl(CareerRepository careerRepository) { this.careerRepository = careerRepository; } @Override public Career save(Career career) { log.debug("Request to save Career : {}", career); return careerRepository.save(career); } @Override public Optional<Career> partialUpdate(Career career) { log.debug("Request to partially update Career : {}", career); return careerRepository .findById(career.getId()) .map( existingCareer -> { if (career.getName() != null) { existingCareer.setName(career.getName()); } return existingCareer; } ) .map(careerRepository::save); } @Override @Transactional(readOnly = true) public Page<Career> findAll(Pageable pageable) { log.debug("Request to get all Careers"); return careerRepository.findAll(pageable); } @Override @Transactional(readOnly = true) public Optional<Career> findOne(Long id) { log.debug("Request to get Career : {}", id); return careerRepository.findById(id); } @Override public void delete(Long id) { log.debug("Request to delete Career : {}", id); careerRepository.deleteById(id); } } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/web/rest/CharacterResource.java package com.iledeslegendes.charactersheet.web.rest; import com.iledeslegendes.charactersheet.domain.Character; import com.iledeslegendes.charactersheet.repository.CharacterRepository; import com.iledeslegendes.charactersheet.service.CharacterService; import com.iledeslegendes.charactersheet.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.iledeslegendes.charactersheet.domain.Character}. */ @RestController @RequestMapping("/api") public class CharacterResource { private final Logger log = LoggerFactory.getLogger(CharacterResource.class); private static final String ENTITY_NAME = "character"; @Value("${jhipster.clientApp.name}") private String applicationName; private final CharacterService characterService; private final CharacterRepository characterRepository; public CharacterResource(CharacterService characterService, CharacterRepository characterRepository) { this.characterService = characterService; this.characterRepository = characterRepository; } /** * {@code POST /characters} : Create a new character. * * @param character the character to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new character, or with status {@code 400 (Bad Request)} if the character has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/characters") public ResponseEntity<Character> createCharacter(@Valid @RequestBody Character character) throws URISyntaxException { log.debug("REST request to save Character : {}", character); if (character.getId() != null) { throw new BadRequestAlertException("A new character cannot already have an ID", ENTITY_NAME, "idexists"); } Character result = characterService.save(character); return ResponseEntity .created(new URI("/api/characters/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /characters/:id} : Updates an existing character. * * @param id the id of the character to save. * @param character the character to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated character, * or with status {@code 400 (Bad Request)} if the character is not valid, * or with status {@code 500 (Internal Server Error)} if the character couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/characters/{id}") public ResponseEntity<Character> updateCharacter( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Character character ) throws URISyntaxException { log.debug("REST request to update Character : {}, {}", id, character); if (character.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, character.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!characterRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Character result = characterService.save(character); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, character.getId().toString())) .body(result); } /** * {@code PATCH /characters/:id} : Partial updates given fields of an existing character, field will ignore if it is null * * @param id the id of the character to save. * @param character the character to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated character, * or with status {@code 400 (Bad Request)} if the character is not valid, * or with status {@code 404 (Not Found)} if the character is not found, * or with status {@code 500 (Internal Server Error)} if the character couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/characters/{id}", consumes = "application/merge-patch+json") public ResponseEntity<Character> partialUpdateCharacter( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody Character character ) throws URISyntaxException { log.debug("REST request to partial update Character partially : {}, {}", id, character); if (character.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, character.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!characterRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<Character> result = characterService.partialUpdate(character); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, character.getId().toString()) ); } /** * {@code GET /characters} : get all the characters. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of characters in body. */ @GetMapping("/characters") public ResponseEntity<List<Character>> getAllCharacters(Pageable pageable) { log.debug("REST request to get a page of Characters"); Page<Character> page = characterService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /characters/:id} : get the "id" character. * * @param id the id of the character to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the character, or with status {@code 404 (Not Found)}. */ @GetMapping("/characters/{id}") public ResponseEntity<Character> getCharacter(@PathVariable Long id) { log.debug("REST request to get Character : {}", id); Optional<Character> character = characterService.findOne(id); return ResponseUtil.wrapOrNotFound(character); } /** * {@code DELETE /characters/:id} : delete the "id" character. * * @param id the id of the character to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/characters/{id}") public ResponseEntity<Void> deleteCharacter(@PathVariable Long id) { log.debug("REST request to delete Character : {}", id); characterService.delete(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .build(); } } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/repository/CharacterSkillRepository.java package com.iledeslegendes.charactersheet.repository; import com.iledeslegendes.charactersheet.domain.CharacterSkill; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data SQL repository for the CharacterSkill entity. */ @SuppressWarnings("unused") @Repository public interface CharacterSkillRepository extends JpaRepository<CharacterSkill, Long> {} <file_sep>/src/main/java/com/iledeslegendes/charactersheet/domain/package-info.java /** * JPA domain objects. */ package com.iledeslegendes.charactersheet.domain; <file_sep>/src/main/java/com/iledeslegendes/charactersheet/web/rest/CharacterSkillResource.java package com.iledeslegendes.charactersheet.web.rest; import com.iledeslegendes.charactersheet.domain.CharacterSkill; import com.iledeslegendes.charactersheet.repository.CharacterSkillRepository; import com.iledeslegendes.charactersheet.service.CharacterSkillService; import com.iledeslegendes.charactersheet.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.iledeslegendes.charactersheet.domain.CharacterSkill}. */ @RestController @RequestMapping("/api") public class CharacterSkillResource { private final Logger log = LoggerFactory.getLogger(CharacterSkillResource.class); private static final String ENTITY_NAME = "characterSkill"; @Value("${jhipster.clientApp.name}") private String applicationName; private final CharacterSkillService characterSkillService; private final CharacterSkillRepository characterSkillRepository; public CharacterSkillResource(CharacterSkillService characterSkillService, CharacterSkillRepository characterSkillRepository) { this.characterSkillService = characterSkillService; this.characterSkillRepository = characterSkillRepository; } /** * {@code POST /character-skills} : Create a new characterSkill. * * @param characterSkill the characterSkill to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new characterSkill, or with status {@code 400 (Bad Request)} if the characterSkill has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/character-skills") public ResponseEntity<CharacterSkill> createCharacterSkill(@Valid @RequestBody CharacterSkill characterSkill) throws URISyntaxException { log.debug("REST request to save CharacterSkill : {}", characterSkill); if (characterSkill.getId() != null) { throw new BadRequestAlertException("A new characterSkill cannot already have an ID", ENTITY_NAME, "idexists"); } CharacterSkill result = characterSkillService.save(characterSkill); return ResponseEntity .created(new URI("/api/character-skills/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /character-skills/:id} : Updates an existing characterSkill. * * @param id the id of the characterSkill to save. * @param characterSkill the characterSkill to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated characterSkill, * or with status {@code 400 (Bad Request)} if the characterSkill is not valid, * or with status {@code 500 (Internal Server Error)} if the characterSkill couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/character-skills/{id}") public ResponseEntity<CharacterSkill> updateCharacterSkill( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody CharacterSkill characterSkill ) throws URISyntaxException { log.debug("REST request to update CharacterSkill : {}, {}", id, characterSkill); if (characterSkill.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, characterSkill.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!characterSkillRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } CharacterSkill result = characterSkillService.save(characterSkill); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, characterSkill.getId().toString())) .body(result); } /** * {@code PATCH /character-skills/:id} : Partial updates given fields of an existing characterSkill, field will ignore if it is null * * @param id the id of the characterSkill to save. * @param characterSkill the characterSkill to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated characterSkill, * or with status {@code 400 (Bad Request)} if the characterSkill is not valid, * or with status {@code 404 (Not Found)} if the characterSkill is not found, * or with status {@code 500 (Internal Server Error)} if the characterSkill couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/character-skills/{id}", consumes = "application/merge-patch+json") public ResponseEntity<CharacterSkill> partialUpdateCharacterSkill( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody CharacterSkill characterSkill ) throws URISyntaxException { log.debug("REST request to partial update CharacterSkill partially : {}, {}", id, characterSkill); if (characterSkill.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, characterSkill.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!characterSkillRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<CharacterSkill> result = characterSkillService.partialUpdate(characterSkill); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, characterSkill.getId().toString()) ); } /** * {@code GET /character-skills} : get all the characterSkills. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of characterSkills in body. */ @GetMapping("/character-skills") public ResponseEntity<List<CharacterSkill>> getAllCharacterSkills(Pageable pageable) { log.debug("REST request to get a page of CharacterSkills"); Page<CharacterSkill> page = characterSkillService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /character-skills/:id} : get the "id" characterSkill. * * @param id the id of the characterSkill to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the characterSkill, or with status {@code 404 (Not Found)}. */ @GetMapping("/character-skills/{id}") public ResponseEntity<CharacterSkill> getCharacterSkill(@PathVariable Long id) { log.debug("REST request to get CharacterSkill : {}", id); Optional<CharacterSkill> characterSkill = characterSkillService.findOne(id); return ResponseUtil.wrapOrNotFound(characterSkill); } /** * {@code DELETE /character-skills/:id} : delete the "id" characterSkill. * * @param id the id of the characterSkill to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/character-skills/{id}") public ResponseEntity<Void> deleteCharacterSkill(@PathVariable Long id) { log.debug("REST request to delete CharacterSkill : {}", id); characterSkillService.delete(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .build(); } } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/service/DeityService.java package com.iledeslegendes.charactersheet.service; import com.iledeslegendes.charactersheet.domain.Deity; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * Service Interface for managing {@link Deity}. */ public interface DeityService { /** * Save a deity. * * @param deity the entity to save. * @return the persisted entity. */ Deity save(Deity deity); /** * Partially updates a deity. * * @param deity the entity to update partially. * @return the persisted entity. */ Optional<Deity> partialUpdate(Deity deity); /** * Get all the deities. * * @param pageable the pagination information. * @return the list of entities. */ Page<Deity> findAll(Pageable pageable); /** * Get the "id" deity. * * @param id the id of the entity. * @return the entity. */ Optional<Deity> findOne(Long id); /** * Delete the "id" deity. * * @param id the id of the entity. */ void delete(Long id); } <file_sep>/src/main/webapp/app/shared/model/character.model.ts import { IDeity } from 'app/shared/model/deity.model'; import { IRace } from 'app/shared/model/race.model'; import { ICareer } from 'app/shared/model/career.model'; import { IItem } from 'app/shared/model/item.model'; import { ICharacterSkill } from 'app/shared/model/character-skill.model'; import { Alignment } from 'app/shared/model/enumerations/alignment.model'; export interface ICharacter { id?: number; name?: string; alignment?: Alignment; experience?: number; party?: string | null; deity?: IDeity | null; blood?: IDeity | null; race?: IRace | null; career?: ICareer | null; inventories?: IItem[] | null; skills?: ICharacterSkill[] | null; } export const defaultValue: Readonly<ICharacter> = {}; <file_sep>/src/test/java/com/iledeslegendes/charactersheet/web/rest/CareerResourceIT.java package com.iledeslegendes.charactersheet.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.iledeslegendes.charactersheet.IntegrationTest; import com.iledeslegendes.charactersheet.domain.Career; import com.iledeslegendes.charactersheet.repository.CareerRepository; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link CareerResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class CareerResourceIT { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final String ENTITY_API_URL = "/api/careers"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private CareerRepository careerRepository; @Autowired private EntityManager em; @Autowired private MockMvc restCareerMockMvc; private Career career; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Career createEntity(EntityManager em) { Career career = new Career().name(DEFAULT_NAME); return career; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Career createUpdatedEntity(EntityManager em) { Career career = new Career().name(UPDATED_NAME); return career; } @BeforeEach public void initTest() { career = createEntity(em); } @Test @Transactional void createCareer() throws Exception { int databaseSizeBeforeCreate = careerRepository.findAll().size(); // Create the Career restCareerMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(career))) .andExpect(status().isCreated()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeCreate + 1); Career testCareer = careerList.get(careerList.size() - 1); assertThat(testCareer.getName()).isEqualTo(DEFAULT_NAME); } @Test @Transactional void createCareerWithExistingId() throws Exception { // Create the Career with an existing ID career.setId(1L); int databaseSizeBeforeCreate = careerRepository.findAll().size(); // An entity with an existing ID cannot be created, so this API call must fail restCareerMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(career))) .andExpect(status().isBadRequest()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional void checkNameIsRequired() throws Exception { int databaseSizeBeforeTest = careerRepository.findAll().size(); // set the field null career.setName(null); // Create the Career, which fails. restCareerMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(career))) .andExpect(status().isBadRequest()); List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeTest); } @Test @Transactional void getAllCareers() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); // Get all the careerList restCareerMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(career.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))); } @Test @Transactional void getCareer() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); // Get the career restCareerMockMvc .perform(get(ENTITY_API_URL_ID, career.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(career.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME)); } @Test @Transactional void getNonExistingCareer() throws Exception { // Get the career restCareerMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putNewCareer() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); int databaseSizeBeforeUpdate = careerRepository.findAll().size(); // Update the career Career updatedCareer = careerRepository.findById(career.getId()).get(); // Disconnect from session so that the updates on updatedCareer are not directly saved in db em.detach(updatedCareer); updatedCareer.name(UPDATED_NAME); restCareerMockMvc .perform( put(ENTITY_API_URL_ID, updatedCareer.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedCareer)) ) .andExpect(status().isOk()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); Career testCareer = careerList.get(careerList.size() - 1); assertThat(testCareer.getName()).isEqualTo(UPDATED_NAME); } @Test @Transactional void putNonExistingCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCareerMockMvc .perform( put(ENTITY_API_URL_ID, career.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(career)) ) .andExpect(status().isBadRequest()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCareerMockMvc .perform( put(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(career)) ) .andExpect(status().isBadRequest()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCareerMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(career))) .andExpect(status().isMethodNotAllowed()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateCareerWithPatch() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); int databaseSizeBeforeUpdate = careerRepository.findAll().size(); // Update the career using partial update Career partialUpdatedCareer = new Career(); partialUpdatedCareer.setId(career.getId()); partialUpdatedCareer.name(UPDATED_NAME); restCareerMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCareer.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedCareer)) ) .andExpect(status().isOk()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); Career testCareer = careerList.get(careerList.size() - 1); assertThat(testCareer.getName()).isEqualTo(UPDATED_NAME); } @Test @Transactional void fullUpdateCareerWithPatch() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); int databaseSizeBeforeUpdate = careerRepository.findAll().size(); // Update the career using partial update Career partialUpdatedCareer = new Career(); partialUpdatedCareer.setId(career.getId()); partialUpdatedCareer.name(UPDATED_NAME); restCareerMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCareer.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedCareer)) ) .andExpect(status().isOk()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); Career testCareer = careerList.get(careerList.size() - 1); assertThat(testCareer.getName()).isEqualTo(UPDATED_NAME); } @Test @Transactional void patchNonExistingCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCareerMockMvc .perform( patch(ENTITY_API_URL_ID, career.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(career)) ) .andExpect(status().isBadRequest()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCareerMockMvc .perform( patch(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(career)) ) .andExpect(status().isBadRequest()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamCareer() throws Exception { int databaseSizeBeforeUpdate = careerRepository.findAll().size(); career.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCareerMockMvc .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(career))) .andExpect(status().isMethodNotAllowed()); // Validate the Career in the database List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void deleteCareer() throws Exception { // Initialize the database careerRepository.saveAndFlush(career); int databaseSizeBeforeDelete = careerRepository.findAll().size(); // Delete the career restCareerMockMvc .perform(delete(ENTITY_API_URL_ID, career.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<Career> careerList = careerRepository.findAll(); assertThat(careerList).hasSize(databaseSizeBeforeDelete - 1); } } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/web/rest/DeityResource.java package com.iledeslegendes.charactersheet.web.rest; import com.iledeslegendes.charactersheet.domain.Deity; import com.iledeslegendes.charactersheet.repository.DeityRepository; import com.iledeslegendes.charactersheet.service.DeityService; import com.iledeslegendes.charactersheet.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.iledeslegendes.charactersheet.domain.Deity}. */ @RestController @RequestMapping("/api") public class DeityResource { private final Logger log = LoggerFactory.getLogger(DeityResource.class); private static final String ENTITY_NAME = "deity"; @Value("${jhipster.clientApp.name}") private String applicationName; private final DeityService deityService; private final DeityRepository deityRepository; public DeityResource(DeityService deityService, DeityRepository deityRepository) { this.deityService = deityService; this.deityRepository = deityRepository; } /** * {@code POST /deities} : Create a new deity. * * @param deity the deity to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new deity, or with status {@code 400 (Bad Request)} if the deity has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/deities") public ResponseEntity<Deity> createDeity(@Valid @RequestBody Deity deity) throws URISyntaxException { log.debug("REST request to save Deity : {}", deity); if (deity.getId() != null) { throw new BadRequestAlertException("A new deity cannot already have an ID", ENTITY_NAME, "idexists"); } Deity result = deityService.save(deity); return ResponseEntity .created(new URI("/api/deities/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /deities/:id} : Updates an existing deity. * * @param id the id of the deity to save. * @param deity the deity to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated deity, * or with status {@code 400 (Bad Request)} if the deity is not valid, * or with status {@code 500 (Internal Server Error)} if the deity couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/deities/{id}") public ResponseEntity<Deity> updateDeity(@PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Deity deity) throws URISyntaxException { log.debug("REST request to update Deity : {}, {}", id, deity); if (deity.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, deity.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!deityRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Deity result = deityService.save(deity); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, deity.getId().toString())) .body(result); } /** * {@code PATCH /deities/:id} : Partial updates given fields of an existing deity, field will ignore if it is null * * @param id the id of the deity to save. * @param deity the deity to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated deity, * or with status {@code 400 (Bad Request)} if the deity is not valid, * or with status {@code 404 (Not Found)} if the deity is not found, * or with status {@code 500 (Internal Server Error)} if the deity couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/deities/{id}", consumes = "application/merge-patch+json") public ResponseEntity<Deity> partialUpdateDeity( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody Deity deity ) throws URISyntaxException { log.debug("REST request to partial update Deity partially : {}, {}", id, deity); if (deity.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, deity.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!deityRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<Deity> result = deityService.partialUpdate(deity); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, deity.getId().toString()) ); } /** * {@code GET /deities} : get all the deities. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of deities in body. */ @GetMapping("/deities") public ResponseEntity<List<Deity>> getAllDeities(Pageable pageable) { log.debug("REST request to get a page of Deities"); Page<Deity> page = deityService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /deities/:id} : get the "id" deity. * * @param id the id of the deity to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the deity, or with status {@code 404 (Not Found)}. */ @GetMapping("/deities/{id}") public ResponseEntity<Deity> getDeity(@PathVariable Long id) { log.debug("REST request to get Deity : {}", id); Optional<Deity> deity = deityService.findOne(id); return ResponseUtil.wrapOrNotFound(deity); } /** * {@code DELETE /deities/:id} : delete the "id" deity. * * @param id the id of the deity to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/deities/{id}") public ResponseEntity<Void> deleteDeity(@PathVariable Long id) { log.debug("REST request to delete Deity : {}", id); deityService.delete(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .build(); } } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/domain/Item.java package com.iledeslegendes.charactersheet.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import javax.persistence.*; import javax.validation.constraints.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A Item. */ @Entity @Table(name = "item") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Item implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @NotNull @Column(name = "reference", nullable = false) private String reference; @NotNull @Column(name = "name", nullable = false) private String name; @NotNull @Column(name = "comment", nullable = false) private Integer comment; @ManyToOne @JsonIgnoreProperties(value = { "deity", "blood", "race", "career", "inventories", "skills" }, allowSetters = true) private Character owner; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Item id(Long id) { this.id = id; return this; } public String getReference() { return this.reference; } public Item reference(String reference) { this.reference = reference; return this; } public void setReference(String reference) { this.reference = reference; } public String getName() { return this.name; } public Item name(String name) { this.name = name; return this; } public void setName(String name) { this.name = name; } public Integer getComment() { return this.comment; } public Item comment(Integer comment) { this.comment = comment; return this; } public void setComment(Integer comment) { this.comment = comment; } public Character getOwner() { return this.owner; } public Item owner(Character character) { this.setOwner(character); return this; } public void setOwner(Character character) { this.owner = character; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Item)) { return false; } return id != null && id.equals(((Item) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Item{" + "id=" + getId() + ", reference='" + getReference() + "'" + ", name='" + getName() + "'" + ", comment=" + getComment() + "}"; } } <file_sep>/src/test/java/com/iledeslegendes/charactersheet/domain/DeityTest.java package com.iledeslegendes.charactersheet.domain; import static org.assertj.core.api.Assertions.assertThat; import com.iledeslegendes.charactersheet.web.rest.TestUtil; import org.junit.jupiter.api.Test; class DeityTest { @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Deity.class); Deity deity1 = new Deity(); deity1.setId(1L); Deity deity2 = new Deity(); deity2.setId(deity1.getId()); assertThat(deity1).isEqualTo(deity2); deity2.setId(2L); assertThat(deity1).isNotEqualTo(deity2); deity1.setId(null); assertThat(deity1).isNotEqualTo(deity2); } } <file_sep>/src/main/webapp/app/shared/model/character-skill.model.ts import { ICharacter } from 'app/shared/model/character.model'; import { ISkill } from 'app/shared/model/skill.model'; export interface ICharacterSkill { id?: number; event?: string; realCost?: number; owner?: ICharacter | null; skill?: ISkill | null; } export const defaultValue: Readonly<ICharacterSkill> = {}; <file_sep>/src/main/webapp/app/shared/model/enumerations/alignment.model.ts export enum Alignment { LAWFUL_GOOD = 'LAWFUL_GOOD', NEUTRAL_GOOD = 'NEUTRAL_GOOD', CHAOTIC_GOOD = 'CHAOTIC_GOOD', LAWFUL_NEUTRAL = 'LAWFUL_NEUTRAL', NEUTRAL_NEUTRAL = 'NEUTRAL_NEUTRAL', CHAOTIC_NEUTRAL = 'CHAOTIC_NEUTRAL', LAWFUL_EVIL = 'LAWFUL_EVIL', NEUTRAL_EVIL = 'NEUTRAL_EVIL', CHAOTIC_EVIL = 'CHAOTIC_EVIL', } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/service/impl/RaceServiceImpl.java package com.iledeslegendes.charactersheet.service.impl; import com.iledeslegendes.charactersheet.domain.Race; import com.iledeslegendes.charactersheet.repository.RaceRepository; import com.iledeslegendes.charactersheet.service.RaceService; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing {@link Race}. */ @Service @Transactional public class RaceServiceImpl implements RaceService { private final Logger log = LoggerFactory.getLogger(RaceServiceImpl.class); private final RaceRepository raceRepository; public RaceServiceImpl(RaceRepository raceRepository) { this.raceRepository = raceRepository; } @Override public Race save(Race race) { log.debug("Request to save Race : {}", race); return raceRepository.save(race); } @Override public Optional<Race> partialUpdate(Race race) { log.debug("Request to partially update Race : {}", race); return raceRepository .findById(race.getId()) .map( existingRace -> { if (race.getName() != null) { existingRace.setName(race.getName()); } return existingRace; } ) .map(raceRepository::save); } @Override @Transactional(readOnly = true) public Page<Race> findAll(Pageable pageable) { log.debug("Request to get all Races"); return raceRepository.findAll(pageable); } @Override @Transactional(readOnly = true) public Optional<Race> findOne(Long id) { log.debug("Request to get Race : {}", id); return raceRepository.findById(id); } @Override public void delete(Long id) { log.debug("Request to delete Race : {}", id); raceRepository.deleteById(id); } } <file_sep>/src/main/webapp/app/entities/deity/deity.reducer.ts import axios from 'axios'; import { parseHeaderForLinks, loadMoreDataWhenScrolled, ICrudGetAction, ICrudGetAllAction, ICrudPutAction, ICrudDeleteAction, } from 'react-jhipster'; import { cleanEntity } from 'app/shared/util/entity-utils'; import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util'; import { IDeity, defaultValue } from 'app/shared/model/deity.model'; export const ACTION_TYPES = { FETCH_DEITY_LIST: 'deity/FETCH_DEITY_LIST', FETCH_DEITY: 'deity/FETCH_DEITY', CREATE_DEITY: 'deity/CREATE_DEITY', UPDATE_DEITY: 'deity/UPDATE_DEITY', PARTIAL_UPDATE_DEITY: 'deity/PARTIAL_UPDATE_DEITY', DELETE_DEITY: 'deity/DELETE_DEITY', RESET: 'deity/RESET', }; const initialState = { loading: false, errorMessage: null, entities: [] as ReadonlyArray<IDeity>, entity: defaultValue, links: { next: 0 }, updating: false, totalItems: 0, updateSuccess: false, }; export type DeityState = Readonly<typeof initialState>; // Reducer export default (state: DeityState = initialState, action): DeityState => { switch (action.type) { case REQUEST(ACTION_TYPES.FETCH_DEITY_LIST): case REQUEST(ACTION_TYPES.FETCH_DEITY): return { ...state, errorMessage: null, updateSuccess: false, loading: true, }; case REQUEST(ACTION_TYPES.CREATE_DEITY): case REQUEST(ACTION_TYPES.UPDATE_DEITY): case REQUEST(ACTION_TYPES.DELETE_DEITY): case REQUEST(ACTION_TYPES.PARTIAL_UPDATE_DEITY): return { ...state, errorMessage: null, updateSuccess: false, updating: true, }; case FAILURE(ACTION_TYPES.FETCH_DEITY_LIST): case FAILURE(ACTION_TYPES.FETCH_DEITY): case FAILURE(ACTION_TYPES.CREATE_DEITY): case FAILURE(ACTION_TYPES.UPDATE_DEITY): case FAILURE(ACTION_TYPES.PARTIAL_UPDATE_DEITY): case FAILURE(ACTION_TYPES.DELETE_DEITY): return { ...state, loading: false, updating: false, updateSuccess: false, errorMessage: action.payload, }; case SUCCESS(ACTION_TYPES.FETCH_DEITY_LIST): { const links = parseHeaderForLinks(action.payload.headers.link); return { ...state, loading: false, links, entities: loadMoreDataWhenScrolled(state.entities, action.payload.data, links), totalItems: parseInt(action.payload.headers['x-total-count'], 10), }; } case SUCCESS(ACTION_TYPES.FETCH_DEITY): return { ...state, loading: false, entity: action.payload.data, }; case SUCCESS(ACTION_TYPES.CREATE_DEITY): case SUCCESS(ACTION_TYPES.UPDATE_DEITY): case SUCCESS(ACTION_TYPES.PARTIAL_UPDATE_DEITY): return { ...state, updating: false, updateSuccess: true, entity: action.payload.data, }; case SUCCESS(ACTION_TYPES.DELETE_DEITY): return { ...state, updating: false, updateSuccess: true, entity: {}, }; case ACTION_TYPES.RESET: return { ...initialState, }; default: return state; } }; const apiUrl = 'api/deities'; // Actions export const getEntities: ICrudGetAllAction<IDeity> = (page, size, sort) => { const requestUrl = `${apiUrl}${sort ? `?page=${page}&size=${size}&sort=${sort}` : ''}`; return { type: ACTION_TYPES.FETCH_DEITY_LIST, payload: axios.get<IDeity>(`${requestUrl}${sort ? '&' : '?'}cacheBuster=${new Date().getTime()}`), }; }; export const getEntity: ICrudGetAction<IDeity> = id => { const requestUrl = `${apiUrl}/${id}`; return { type: ACTION_TYPES.FETCH_DEITY, payload: axios.get<IDeity>(requestUrl), }; }; export const createEntity: ICrudPutAction<IDeity> = entity => async dispatch => { const result = await dispatch({ type: ACTION_TYPES.CREATE_DEITY, payload: axios.post(apiUrl, cleanEntity(entity)), }); return result; }; export const updateEntity: ICrudPutAction<IDeity> = entity => async dispatch => { const result = await dispatch({ type: ACTION_TYPES.UPDATE_DEITY, payload: axios.put(`${apiUrl}/${entity.id}`, cleanEntity(entity)), }); return result; }; export const partialUpdate: ICrudPutAction<IDeity> = entity => async dispatch => { const result = await dispatch({ type: ACTION_TYPES.PARTIAL_UPDATE_DEITY, payload: axios.patch(`${apiUrl}/${entity.id}`, cleanEntity(entity)), }); return result; }; export const deleteEntity: ICrudDeleteAction<IDeity> = id => async dispatch => { const requestUrl = `${apiUrl}/${id}`; const result = await dispatch({ type: ACTION_TYPES.DELETE_DEITY, payload: axios.delete(requestUrl), }); return result; }; export const reset = () => ({ type: ACTION_TYPES.RESET, }); <file_sep>/src/main/java/com/iledeslegendes/charactersheet/domain/CharacterSkill.java package com.iledeslegendes.charactersheet.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import javax.persistence.*; import javax.validation.constraints.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A CharacterSkill. */ @Entity @Table(name = "character_skill") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class CharacterSkill implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @NotNull @Column(name = "event", nullable = false) private String event; @NotNull @Column(name = "real_cost", nullable = false) private Integer realCost; @ManyToOne @JsonIgnoreProperties(value = { "deity", "blood", "race", "career", "inventories", "skills" }, allowSetters = true) private Character owner; @ManyToOne @JsonIgnoreProperties(value = { "racialCondition", "careerCondition", "skillCondition" }, allowSetters = true) private Skill skill; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public CharacterSkill id(Long id) { this.id = id; return this; } public String getEvent() { return this.event; } public CharacterSkill event(String event) { this.event = event; return this; } public void setEvent(String event) { this.event = event; } public Integer getRealCost() { return this.realCost; } public CharacterSkill realCost(Integer realCost) { this.realCost = realCost; return this; } public void setRealCost(Integer realCost) { this.realCost = realCost; } public Character getOwner() { return this.owner; } public CharacterSkill owner(Character character) { this.setOwner(character); return this; } public void setOwner(Character character) { this.owner = character; } public Skill getSkill() { return this.skill; } public CharacterSkill skill(Skill skill) { this.setSkill(skill); return this; } public void setSkill(Skill skill) { this.skill = skill; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CharacterSkill)) { return false; } return id != null && id.equals(((CharacterSkill) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "CharacterSkill{" + "id=" + getId() + ", event='" + getEvent() + "'" + ", realCost=" + getRealCost() + "}"; } } <file_sep>/src/test/java/com/iledeslegendes/charactersheet/IntegrationTest.java package com.iledeslegendes.charactersheet; import com.iledeslegendes.charactersheet.CharacterSheetApp; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.test.context.SpringBootTest; /** * Base composite annotation for integration tests. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @SpringBootTest(classes = CharacterSheetApp.class) public @interface IntegrationTest { } <file_sep>/src/main/java/com/iledeslegendes/charactersheet/repository/DeityRepository.java package com.iledeslegendes.charactersheet.repository; import com.iledeslegendes.charactersheet.domain.Deity; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data SQL repository for the Deity entity. */ @SuppressWarnings("unused") @Repository public interface DeityRepository extends JpaRepository<Deity, Long> {} <file_sep>/src/test/resources/i18n/messages_fr.properties email.test.title=Activation de votre compte CharacterSheet <file_sep>/src/test/java/com/iledeslegendes/charactersheet/web/rest/CharacterSkillResourceIT.java package com.iledeslegendes.charactersheet.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.iledeslegendes.charactersheet.IntegrationTest; import com.iledeslegendes.charactersheet.domain.CharacterSkill; import com.iledeslegendes.charactersheet.repository.CharacterSkillRepository; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link CharacterSkillResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class CharacterSkillResourceIT { private static final String DEFAULT_EVENT = "AAAAAAAAAA"; private static final String UPDATED_EVENT = "BBBBBBBBBB"; private static final Integer DEFAULT_REAL_COST = 1; private static final Integer UPDATED_REAL_COST = 2; private static final String ENTITY_API_URL = "/api/character-skills"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private CharacterSkillRepository characterSkillRepository; @Autowired private EntityManager em; @Autowired private MockMvc restCharacterSkillMockMvc; private CharacterSkill characterSkill; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static CharacterSkill createEntity(EntityManager em) { CharacterSkill characterSkill = new CharacterSkill().event(DEFAULT_EVENT).realCost(DEFAULT_REAL_COST); return characterSkill; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static CharacterSkill createUpdatedEntity(EntityManager em) { CharacterSkill characterSkill = new CharacterSkill().event(UPDATED_EVENT).realCost(UPDATED_REAL_COST); return characterSkill; } @BeforeEach public void initTest() { characterSkill = createEntity(em); } @Test @Transactional void createCharacterSkill() throws Exception { int databaseSizeBeforeCreate = characterSkillRepository.findAll().size(); // Create the CharacterSkill restCharacterSkillMockMvc .perform( post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isCreated()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeCreate + 1); CharacterSkill testCharacterSkill = characterSkillList.get(characterSkillList.size() - 1); assertThat(testCharacterSkill.getEvent()).isEqualTo(DEFAULT_EVENT); assertThat(testCharacterSkill.getRealCost()).isEqualTo(DEFAULT_REAL_COST); } @Test @Transactional void createCharacterSkillWithExistingId() throws Exception { // Create the CharacterSkill with an existing ID characterSkill.setId(1L); int databaseSizeBeforeCreate = characterSkillRepository.findAll().size(); // An entity with an existing ID cannot be created, so this API call must fail restCharacterSkillMockMvc .perform( post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional void checkEventIsRequired() throws Exception { int databaseSizeBeforeTest = characterSkillRepository.findAll().size(); // set the field null characterSkill.setEvent(null); // Create the CharacterSkill, which fails. restCharacterSkillMockMvc .perform( post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeTest); } @Test @Transactional void checkRealCostIsRequired() throws Exception { int databaseSizeBeforeTest = characterSkillRepository.findAll().size(); // set the field null characterSkill.setRealCost(null); // Create the CharacterSkill, which fails. restCharacterSkillMockMvc .perform( post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeTest); } @Test @Transactional void getAllCharacterSkills() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); // Get all the characterSkillList restCharacterSkillMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(characterSkill.getId().intValue()))) .andExpect(jsonPath("$.[*].event").value(hasItem(DEFAULT_EVENT))) .andExpect(jsonPath("$.[*].realCost").value(hasItem(DEFAULT_REAL_COST))); } @Test @Transactional void getCharacterSkill() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); // Get the characterSkill restCharacterSkillMockMvc .perform(get(ENTITY_API_URL_ID, characterSkill.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(characterSkill.getId().intValue())) .andExpect(jsonPath("$.event").value(DEFAULT_EVENT)) .andExpect(jsonPath("$.realCost").value(DEFAULT_REAL_COST)); } @Test @Transactional void getNonExistingCharacterSkill() throws Exception { // Get the characterSkill restCharacterSkillMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putNewCharacterSkill() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); // Update the characterSkill CharacterSkill updatedCharacterSkill = characterSkillRepository.findById(characterSkill.getId()).get(); // Disconnect from session so that the updates on updatedCharacterSkill are not directly saved in db em.detach(updatedCharacterSkill); updatedCharacterSkill.event(UPDATED_EVENT).realCost(UPDATED_REAL_COST); restCharacterSkillMockMvc .perform( put(ENTITY_API_URL_ID, updatedCharacterSkill.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedCharacterSkill)) ) .andExpect(status().isOk()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); CharacterSkill testCharacterSkill = characterSkillList.get(characterSkillList.size() - 1); assertThat(testCharacterSkill.getEvent()).isEqualTo(UPDATED_EVENT); assertThat(testCharacterSkill.getRealCost()).isEqualTo(UPDATED_REAL_COST); } @Test @Transactional void putNonExistingCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform( put(ENTITY_API_URL_ID, characterSkill.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform( put(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(characterSkill))) .andExpect(status().isMethodNotAllowed()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateCharacterSkillWithPatch() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); // Update the characterSkill using partial update CharacterSkill partialUpdatedCharacterSkill = new CharacterSkill(); partialUpdatedCharacterSkill.setId(characterSkill.getId()); restCharacterSkillMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCharacterSkill.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedCharacterSkill)) ) .andExpect(status().isOk()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); CharacterSkill testCharacterSkill = characterSkillList.get(characterSkillList.size() - 1); assertThat(testCharacterSkill.getEvent()).isEqualTo(DEFAULT_EVENT); assertThat(testCharacterSkill.getRealCost()).isEqualTo(DEFAULT_REAL_COST); } @Test @Transactional void fullUpdateCharacterSkillWithPatch() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); // Update the characterSkill using partial update CharacterSkill partialUpdatedCharacterSkill = new CharacterSkill(); partialUpdatedCharacterSkill.setId(characterSkill.getId()); partialUpdatedCharacterSkill.event(UPDATED_EVENT).realCost(UPDATED_REAL_COST); restCharacterSkillMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCharacterSkill.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedCharacterSkill)) ) .andExpect(status().isOk()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); CharacterSkill testCharacterSkill = characterSkillList.get(characterSkillList.size() - 1); assertThat(testCharacterSkill.getEvent()).isEqualTo(UPDATED_EVENT); assertThat(testCharacterSkill.getRealCost()).isEqualTo(UPDATED_REAL_COST); } @Test @Transactional void patchNonExistingCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform( patch(ENTITY_API_URL_ID, characterSkill.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform( patch(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isBadRequest()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamCharacterSkill() throws Exception { int databaseSizeBeforeUpdate = characterSkillRepository.findAll().size(); characterSkill.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCharacterSkillMockMvc .perform( patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(characterSkill)) ) .andExpect(status().isMethodNotAllowed()); // Validate the CharacterSkill in the database List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void deleteCharacterSkill() throws Exception { // Initialize the database characterSkillRepository.saveAndFlush(characterSkill); int databaseSizeBeforeDelete = characterSkillRepository.findAll().size(); // Delete the characterSkill restCharacterSkillMockMvc .perform(delete(ENTITY_API_URL_ID, characterSkill.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<CharacterSkill> characterSkillList = characterSkillRepository.findAll(); assertThat(characterSkillList).hasSize(databaseSizeBeforeDelete - 1); } }
e021a736f390320b1f7bcc11eac0d1d22a023a06
[ "Java", "TypeScript", "INI" ]
24
Java
maximeso/character-sheet
f0bc7badc49b9e81860a2d2b6da8bc92fe8d5f61
a6da6a5abb079916dd1e2dff11096cc3e75f3e4e
refs/heads/master
<repo_name>Elycin/AWSBucketDownloader<file_sep>/README.md # AWSBucketDownloader Tool to download everything in an AWS S3 Bucket ## Purpose This tool was created to assist in orchestration of downloading files to server in a personal project, in a timed basis. ## How it works and how to use - The first initial run will create a configuration file in the current working directory. - Edit the `AWSBucketDownloader.json` it creates with your `AWS_ACCESS_KEY`, `AWS_SECRET_KEY`, `AWS_BUCKET_NAME` and `AWS_REGION`. - Specify the root directory where it should download the files to - Note: it will create a subdirectory with the bucket name. - Run it again to download all the files in the bucket. - Optinally, you can add it to Task Scheduler to haved scheduled updates <file_sep>/AWSHelper.cs using Amazon.Runtime; using Amazon.S3; using BucketDownloaderAWS; using System; namespace AWSBucketDownloader { internal class AWSHelper { /// <summary> /// Converts string based AWS regions into their proper types. /// </summary> /// <param name="endpoint"></param> /// <returns></returns> private static Amazon.RegionEndpoint ParseRegion(string endpoint) { switch (endpoint) { case "us-east-1": return Amazon.RegionEndpoint.USEast1; case "us-east-2": return Amazon.RegionEndpoint.USEast2; case "us-west-1": return Amazon.RegionEndpoint.USWest1; case "us-west-2": return Amazon.RegionEndpoint.USWest2; case "ap-northeast-1": return Amazon.RegionEndpoint.APNortheast1; case "ap-northeast-2": return Amazon.RegionEndpoint.APNortheast2; case "ap-south-1": return Amazon.RegionEndpoint.APSouth1; case "ap-southeast-1": return Amazon.RegionEndpoint.APSoutheast1; case "ap-southeast-2": return Amazon.RegionEndpoint.APSoutheast2; case "ca-central-1": return Amazon.RegionEndpoint.CACentral1; case "cn-north-1": return Amazon.RegionEndpoint.CNNorth1; case "cn-northwest-1": return Amazon.RegionEndpoint.CNNorthWest1; case "eu-central-1": return Amazon.RegionEndpoint.EUCentral1; case "eu-west-1": return Amazon.RegionEndpoint.EUWest1; case "eu-west-2": return Amazon.RegionEndpoint.EUWest2; case "eu-west-3": return Amazon.RegionEndpoint.EUWest3; case "sa-east-1": return Amazon.RegionEndpoint.SAEast1; default: Console.WriteLine("Invalid AWS Region specified."); Console.ReadLine(); Environment.Exit(1); return null; } } /// <summary> /// Builds a BasicAWSCredentials instance with the proper variables for the bucket. /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static BasicAWSCredentials BuildAWSCredentialHandler(Configuration configuration) => new BasicAWSCredentials(configuration.GetAWSAccessKey(), configuration.GetAWSSecretKey()); /// <summary> /// Builds a AmazonS3Config instance with the proper variables for the region. /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static AmazonS3Config BuildAWSConfiguration(Configuration configuration) => new AmazonS3Config { RegionEndpoint = ParseRegion(configuration.GetAWSRegion()) }; } }<file_sep>/Configuration.cs using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BucketDownloaderAWS { class Configuration { /// <summary> /// The variable that contains the loaded configuration. /// </summary> private JObject loadedConfiguration; /// <summary> /// Constructor that handles the base logic of the configuration initialization and loading. /// </summary> public Configuration() { Console.WriteLine("Configuration class initialized"); if (DoesConfigurationExist()) { // Read the configuration into memory. ReadConfiguration(); } else { // Create and write the new configuration. CreateConfiguration(); WriteConfiguration(); // Tell the user what they need to do Console.WriteLine(); Console.WriteLine("Please edit the configuration and restart the application."); Console.WriteLine("Press enter to exit."); Console.ReadLine(); // Graceful exit. Environment.Exit(0); } } /// <summary> /// Creates a new configuration and loads it into memory. /// </summary> public void CreateConfiguration() { // Create a template formt he bucket. JObject newBucketSubConfiguration = new JObject { { "Bucket Name", "YOUR_BUCKET_NAME" }, { "Access Key", "YOUR_ACCESS_KEY" }, { "Secret Key", "YOUR_SECRET_KEY" }, { "Region", "us-east-2" } }; // Create the base configuration that we will write to the filesystem. JObject newConfiguration = new JObject { { "AWS", newBucketSubConfiguration }, { "Save Path", "C:/Users/Adminsitrator/Desktop/S3" }, }; // Assign to the class. loadedConfiguration = newConfiguration; Console.WriteLine("A new configuration template has been created."); } public void ReadConfiguration() { loadedConfiguration = JObject.Parse(File.ReadAllText(GetConfigurationAbsolutePath())); Console.WriteLine("Configuration has successfully been loaded from the disk."); } /// <summary> /// Writes the loaded configuration in memory to the disk. /// </summary> public void WriteConfiguration() { // Export to a string, but indented. String exportedJSON = loadedConfiguration.ToString(Newtonsoft.Json.Formatting.Indented); // Write to the filesystem File.WriteAllText(GetConfigurationAbsolutePath(), exportedJSON); // Write to console where it was saved. Console.WriteLine(String.Format("Configuration saved: {0}", GetConfigurationAbsolutePath())); } /// <summary> /// Checks to see if the configuration exists. /// </summary> /// <returns></returns> public bool DoesConfigurationExist() => File.Exists(GetConfigurationAbsolutePath()); /// <summary> /// Get the working directory of the configuration. /// </summary> /// <returns></returns> public string GetConfigurationPath() => Directory.GetCurrentDirectory(); /// <summary> /// Get the absolute path to the configuration. /// </summary> /// <returns></returns> public string GetConfigurationAbsolutePath() => Path.Combine(GetConfigurationPath(), "AWSBucketDownloader.json"); /// <summary> /// Get the bucket name from the configuration. /// </summary> /// <returns></returns> public string GetAWSS3BucketName() => loadedConfiguration["AWS"]["Bucket Name"].ToString(); /// <summary> /// Get the access key from the configuration. /// </summary> /// <returns></returns> public string GetAWSAccessKey() => loadedConfiguration["AWS"]["Access Key"].ToString(); /// <summary> /// Get the secret key from the configuration. /// </summary> /// <returns></returns> public string GetAWSSecretKey() => loadedConfiguration["AWS"]["Secret Key"].ToString(); /// <summary> /// Return the region /// </summary> /// <returns></returns> public string GetAWSRegion() => loadedConfiguration["AWS"]["Region"].ToString(); /// <summary> /// Return the save location. /// </summary> /// <returns></returns> public string GetSaveLocation() => loadedConfiguration["Save Path"].ToString(); /// <summary> /// Return the save location with the bucket name. /// </summary> /// <returns></returns> public string GetSaveLocationWithBucket() => Path.Combine(GetSaveLocation(), GetAWSS3BucketName()); } } <file_sep>/Program.cs using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using AWSBucketDownloader; using System; using System.IO; using System.Threading; namespace BucketDownloaderAWS { internal class Program { private static Configuration configuration; private static void Main(string[] args) { // Initialize a new configuration class configuration = new Configuration(); // Download the object. DownloadAllObjects(); Console.WriteLine(new String('=', Console.BufferWidth - 1)); Console.WriteLine("\nClosing gracefully in 10 seconds."); Thread.Sleep(10000); Environment.Exit(0); } public static void DownloadAllObjects() { using (IAmazonS3 AmazonNetworkClient = new AmazonS3Client(AWSHelper.BuildAWSCredentialHandler(configuration), AWSHelper.BuildAWSConfiguration(configuration))) { // Compile a list of objects. ListObjectsRequest request = new ListObjectsRequest { BucketName = configuration.GetAWSS3BucketName() }; ListObjectsResponse response = AmazonNetworkClient.ListObjects(request); // Make sure the save location exists if (Directory.Exists(configuration.GetSaveLocation())) Directory.CreateDirectory(configuration.GetSaveLocation()); if (Directory.Exists(configuration.GetSaveLocationWithBucket())) Directory.CreateDirectory(configuration.GetSaveLocationWithBucket()); // Add a new line for readability in the console. Console.WriteLine(new String('=', Console.BufferWidth - 1)); // Iterate over each object. foreach (S3Object currentObject in response.S3Objects) { // Get the base name of the file string objectBaseName; if (currentObject.Key.Contains("/")) { string[] split = currentObject.Key.Split('/'); objectBaseName = split[split.Length - 1]; } else { objectBaseName = currentObject.Key; } string combinedPath = Path.Combine(configuration.GetSaveLocationWithBucket(), currentObject.Key); // Check to see if it's a directory. if (!currentObject.Key.EndsWith("/")) { Console.WriteLine("Downloading object: " + objectBaseName); Console.WriteLine("\tBucket Path: /" + currentObject.Key); Console.WriteLine("\tFile Size: " + currentObject.Size / Math.Pow(1024, 1)); Console.WriteLine("\tSave Location: " + combinedPath); // Get information about the object GetObjectResponse objectResponse = AmazonNetworkClient.GetObject( new GetObjectRequest { BucketName = configuration.GetAWSS3BucketName(), Key = currentObject.Key } ); // Write to location objectResponse.WriteResponseStreamToFile(combinedPath); Console.WriteLine(String.Format("{0} has been downloaded successfully.\n", currentObject.Key)); } } } } } }
b9eb3f851f28e046cc8b29bffbef6b1dd0063c3d
[ "Markdown", "C#" ]
4
Markdown
Elycin/AWSBucketDownloader
7089c0235d44f1788da410a019f8627dfac65643
094a22ecb70a81992f67fb38593a8b72bd0d64ed
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { DailyTranService} from '../../Services/daily.service'; import { UUID } from 'angular2-uuid'; import { Router, ActivatedRoute} from '@angular/router'; import { XmlLognService} from '../../Services/xmllog.service'; import { Sorter} from '../../Services/app.sort'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', providers:[DailyTranService,Sorter,XmlLognService] }) export class DashboardComponent { TotalItemUsed: any; TotalProceduresByClient: any; oSetting: any; prev:number=-1; xols:any[]=[ { name:"fileName", title:"XML File Name", sorted:false, sortAs:"", sortable:false }, { name:"receiveTime", title:"Created Time", sorted:false, sortAs:"", sortable:false }, { name:"records.length", title:"No Of Records", sorted:false, sortAs:"", sortable:false }, ] cols:any[]=[ { name:"receiveTime", title:"File Receive Time", sorted:false, sortAs:"", sortable:false }, { name:"fileName", title:"Transaction File Name", sorted:false, sortAs:"", sortable:false }, { name:"records.length", title:"Total/New", sorted:false, sortAs:"", sortable:false }, ]; Dailytrans: any[]; Xmlhistory:any[]; clientItemList:any[]; constructor(private userService: DailyTranService,private sortService:Sorter ,private XmlService: XmlLognService ) { userService.GetDailyTran().subscribe(m => { this.Dailytrans = m; this.sortService.direction=1; this.sortService.sort(this.cols[0],this.Dailytrans); }); XmlService.GetXmlLog().subscribe( h => { this.Xmlhistory = h; this.sortService.direction=1; this.sortService.sort(this.cols[0],this.Xmlhistory); }); this.TotalItemUsed= { data: [{ data: [65, 59, 80, 81, 56, 55, 40], label: 2016 }, { data: [28, 48, 40, 19, 86, 27, 90], label: 2016 }], label: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; this.TotalProceduresByClient= { data: [{ data: [65, 59, 80, 81, 56, 55, 40], label: 2016 }, { data: [28, 48, 40, 19, 86, 27, 90], label: 2016 }], label: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; this.clientItemList=[{id:'1',name:'Amrik'}]; } getNew(records) { return records.filter(m=>m.IsNew==true).length; } SortColumn(key) { this.sortService.sort(key,this.Dailytrans); } XortColumn(key) { this.sortService.sort(key,this.Xmlhistory); } } <file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/map"; @Injectable() export class XmlLognService { constructor(private http: Http) {} GetXmlLog(){ return this.http.get("/api/xmllog").map(res=>res.json()); } SaveXmlLog(data){ return this.http.post("/api/xmllog",data).map(res=>res.json()); } UpdateXmlLog(data){ return this.http.put("/api/xmllog/"+data.id,data).map(res=>res.json()); } DeleteXmlLog(data){ return this.http.delete("/api/xmllog/"+data.id,data).map(res=>res.json()); } Resend(id){ return this.http.get("/api/xmlresend/"+id).map(res=>res.json()); } ResendB(id){ return this.http.get("/api/xmlresendb/"+id).map(res=>res.json()); } } <file_sep>var jFile = require('jsonfile'); var filePath = './DataDB/country.code.json'; var uuidV1 = require('uuid/v1'); var dateFormat = require('dateformat'); var XLSX = require('xlsx'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); var CountryDB = { GetCountry: function (req, res) { fs.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); var ddd = "[" + obj.toString().substr(0, obj.toString().length - 1) + "]"; // console.log(ddd); res.json(JSON.parse(ddd)); }); }, SaveCountry: function (data, fileName, ClientName, cb) { var str = JSON.stringify(data); str = str.substr(1, str.length - 2); fs.writeFile(filePath, str + ",", function (err) { if (err == null) cb("{\"Status\":\"OK\"}"); }); }, DeleteDaily: function (req, res) { console.log('Data Record', req.body); jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.id == req.params.id); }); index = obj.indexOf(index[0]); console.log('Index Of Record', index); if (index > -1) { obj.splice(index, 1); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } else { res.json(obj); } }); }, UpdateDaily: function (req, res) { jFile.readFile(filePath, function (err, obj) { console.log(req.body.id) index = obj.filter(function (item) { return (item.id == req.body.id); }); index = obj.indexOf(index[0]); if (index > -1) { obj[index] = req.body; jFile.writeFile(filePath, obj, {}, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } }); }, GetUnCode: function (COUNTRY, LOCNAME, SUBDIV, cb) { fs.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); var ddd = JSON.parse("[" + obj.toString().substr(0, obj.toString().length - 1) + "]"); var res = index = ddd.filter(function (item) { return (item.COUNTRY.toString().toLowerCase() == COUNTRY.toString().toLowerCase() && item.LOCNAME.toString().toLowerCase() == LOCNAME.toString().toLowerCase() && item.SUBDIV.toString().toLowerCase() == SUBDIV.toString().toLowerCase()); }); if (res.length > 0) cb(res[0]); else cb(null); }); }, ProcessCountryExcel: function () { var basePath = __dirname.replace("SERVICE", "DataDB"); console.log("base path", basePath); var SourceFile = basePath + "\\CountryDB.xls"; console.log("Process Filem", SourceFile); // console.log("Source File Path", SourceFile); if (fs.existsSync(SourceFile)) { console.log("Yes Exist"); ReadCountryExcel(SourceFile, "Dummay", function (excelData) { fs.renameSync(SourceFile, basePath + "\\CountryDB_.xls"); CountryDB.SaveCountry(excelData, "", "", function () { }); // Country Save }); // Country Read Excel Data } }, download: function (req, res) { fs.readFile(filePath, function (err, obj) { if (err) var ddd = "[" + obj.toString().substr(0, obj.toString().length - 1) + "]"; var basePath = __dirname.replace("Service", "DataDB"); var SourceFile = basePath + "\\CountryDB.xls"; file = SourceFile; console.log(SourceFile); if (fs.existsSync(SourceFile)) { var filename = path.basename(file); var mimetype = mime.lookup(file); res.setHeader('Content-disposition', 'attachment; filename=' + filename); res.setHeader('Content-type', mimetype); var filestream = fs.createReadStream(file); filestream.pipe(res); } }); } } module.exports = CountryDB; function ReadCountryExcel(InputFile, Client, cb) { var workbook = XLSX.readFile(InputFile); var SheetName = workbook.Props.SheetNames[0]; var dataRows = []; var row = 2; while (GetData(workbook, SheetName, "A" + row) != "") { try { //console.log("Daa",workbook.Sheets.A["Q"+ row]) dataRows.push({ "ID": uuidV1(), "COUNTRY": GetData(workbook, SheetName, "A" + row), "UNCODE": GetData(workbook, SheetName, "B" + row), "LOCNAME": GetData(workbook, SheetName, "C" + row), "SUBDIV": GetData(workbook, SheetName, "D" + row), "IATACODE": GetData(workbook, SheetName, "E" + row), "IATANAME": GetData(workbook, SheetName, "F" + row), "TIMEXONE": GetData(workbook, SheetName, "G" + row), "PORT": GetData(workbook, SheetName, "H" + row), "AIRPORT": GetData(workbook, SheetName, "I" + row), "RAIL": GetData(workbook, SheetName, "J" + row), "ROAD": GetData(workbook, SheetName, "K" + row), "UNSTANDARD": GetData(workbook, SheetName, "L" + row), "LOCALNAME": GetData(workbook, SheetName, "M" + row), "NONIATA": GetData(workbook, SheetName, "N" + row), "VALIDFROM": GetData(workbook, SheetName, "O" + row), "VALIDTO": GetData(workbook, SheetName, "P" + row) }); } catch (ex) { console.log(ex); } row = row + 1; } console.log("Country DB", dataRows.length); cb(dataRows); } function GetData(obj, SheetName, col) { try { return obj.Sheets[SheetName][col].w; //obj.Sheets[SheetName][col].w; } catch (ex) { return ""; } }<file_sep>import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import {CommonModule} from '@angular/common'; import { HttpModule } from '@angular/http'; import { RouterModule} from '@angular/router'; import { UserComponent} from './user.component'; import { Ng2PaginationModule} from 'ng2-pagination'; import { UserFilterPipe } from './user.filter'; import { Ng2TableModule } from 'ng2-table/ng2-table'; import { GridComponent } from '../grid/grid.component'; @NgModule({ declarations: [ UserComponent, UserFilterPipe, GridComponent ], imports: [ FormsModule, CommonModule, HttpModule, Ng2PaginationModule, Ng2TableModule, RouterModule.forRoot([ {path:'user',component:UserComponent} ]), RouterModule ], providers: [], }) export class UserModule { } <file_sep>export class CurrentUser { token:String; user:any; }<file_sep>export class Sorter { direction: number; key: any={}; lastIndex:number=-1; constructor() { this.direction = -1; } sort(key, data) { var name = key.name; console.log("Field",name); if(this.key.name===undefined) { this.direction =this.direction* -1; } else if (this.key.name === name) { this.direction =this.direction* -1; } else { this.direction = 1; } data.sort((a, b) => { if (a[name] != null) { if (b[name] != null) { if (a[name].toString().toLowerCase() === b[name].toString().toLowerCase()) { return 0; } else if (a[name].toString().toLowerCase() > b[name].toString().toLowerCase()) { return 1 * this.direction; } else { return -1 * this.direction; } } else { return 1 * this.direction; } } else { return -1 * this.direction; } }); if(this.key.name!=undefined) { this.key.sorted = false; } this.key=key; key.sorted=true; if(this.direction==1) { key.sortAs="fa fa-sort-alpha-asc"; } else { key.sortAs="fa fa-sort-alpha-desc"; } } }<file_sep>var jFile = require('jsonfile'); var filePath = './DataDB/user.json'; var User = { GetUser: function (req, res) { jFile.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); res.json(obj.filter(m=>m.role!="superadmin")) }); }, SaveUser: function (req, res) { // console.log("Data ", req.body) // spoofing the DB response for simplicity jFile.readFile(filePath, function (err, obj) { obj.push(req.body); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); }); }, DeleteUser: function (req, res) { // console.log('Data Record', req.body); jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.id == req.params.id); }); index = obj.indexOf(index[0]); // console.log('Index Of Record', index); if (index > -1) { obj.splice(index, 1); jFile.writeFile(filePath, obj, { }, function (err) { // console.error("rror", err); if (err == null) res.json(obj); }); } else { res.json(obj); } }); }, UpdateUser: function (req, res) { jFile.readFile(filePath, function (err, obj) { console.log(req.body.id) index = obj.filter(function (item) { return (item.id == req.body.id); }); index = obj.indexOf(index[0]); if (index > -1) { obj[index] = req.body; jFile.writeFile(filePath, obj, {}, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } }); }, ValidateUser: function (req,res) { // console.log('ValidateUser Data Record', req.body); jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.userName ==req.body. userName && item.password==req.body.password); }); console.log("RRRR",index); if (index.length==0) { res.json({"status":false,"user":null}) } else { res.json({"status":true,"user":index[0]}); } }); } } module.exports = User;<file_sep>import { Component, Input, Output, EventEmitter, AfterViewInit, AfterViewChecked, OnInit} from '@angular/core'; @Component({ selector: 'my-chart', templateUrl: './chart.base.component.html', // providers: [ReportService] }) export class BasicChartReport implements AfterViewInit, AfterViewChecked, OnInit { @Input() ChartTitle: string; @Input() desc: string="This is small example of todo list"; @Input() ChartData: any; @Output() yearChanged = new EventEmitter(); @Input() HideCustom: boolean = true; @Output() customChanged = new EventEmitter(); @Output() yearChangedForOrder = new EventEmitter(); @Input() ActiveClientList: any; SelectedYear: number; // lineChart public lineChartData: any[]; public lineChartLabels: Array<any>; public lineChartType: string = 'line'; public legend: boolean = true; // YearArrary public Years: Array<any> = []; public CurrentYear: any; public DefaultYear: any; CurrentDate: Number = Date.now(); public randomizeType(): void { this.lineChartType = this.lineChartType === 'line' ? 'bar' : 'line'; } public chartClicked(e: any): void { } public chartHovered(e: any): void { } constructor() { this.ChartData = { data: [{ data: [], label: 2016 }, { data: [], label: 2016 }], label: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; this.lineChartLabels = this.ChartData.label; this.lineChartData = this.ChartData.data; this.CurrentYear = new Date().getFullYear(); this.DefaultYear = new Date().getFullYear(); this.Years = []; this.ActiveClientList = []; } ngOnInit() { this.getAllActiveClient(); this.createRange(); } createRange() { for (var i = this.CurrentYear; i >= 2016; i--) { this.Years.push(i); } return this.Years; } getAllActiveClient() { } ngAfterViewInit() { if (this.ChartData != null) { //this.lineChartLabels = this.ChartData.label; //this.lineChartData = this.ChartData.data; } } ngAfterViewChecked() { if (this.ChartData != null) { //console.log("Chart Data", this.ChartData.data); this.lineChartLabels = this.ChartData.label; this.lineChartData = this.ChartData.data; } } public onYearChange(event) { this.yearChanged.emit(event); this.yearChangedForOrder.emit(event); } public onClientChange(event) { this.customChanged.emit(event); } } <file_sep>import { Component ,AfterViewInit} from '@angular/core'; import { AppGlobals} from '../Services/app.global'; import {StorageService} from '../Services/local.storage'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers:[AppGlobals,StorageService] }) export class AppComponent { title = 'Node Angular 2 Demo'; Login:Boolean; constructor(private appG: AppGlobals){ this.Login= this.appG.GetToken() == undefined ? false :true; } UpdateMaster(IsCheck:boolean){ this.Login=IsCheck; } } <file_sep>import {Injectable} from "@angular/core"; import {Http,Headers} from "@angular/http"; import {Task} from "../DataModel/task" import "rxjs/add/operator/map"; @Injectable() export class TaskService{ constructor(private http:Http){ console.log("Task Service Initialized"); } getTasks(){ return this.http.get("/api/tasks").map(res=>res.json()); } AddTasks(task:Task){ return this.http.post("/api/tasks",task).map(res=>res.json()); } UpdateTask(task:Task){ var header= new Headers(); header.append("Content-Type","application/json"); return this.http.put("/api/tasks/"+task._id,JSON.stringify(task),{headers:header} ).map(res=>res.json()); } DeleteTask(task:Task){ return this.http.delete("/api/tasks/"+task._id).map(res=>res.json()); } } <file_sep>var jFile = require('jsonfile'); var filePath = './DataDB/setting.json'; var Setting = { GetSettingByID:function(id,cb){ jFile.readFile(filePath, function (err, obj) { if (err) console.log("Setting Error", err); cb(obj.filter(m => m.id == id)[0]); }); }, GetSetting: function (req, res) { jFile.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); res.json(obj) }); }, SaveSetting: function (req, res) { console.log("Data ", req.body) // spoofing the DB response for simplicity jFile.readFile(filePath, function (err, obj) { obj.push(req.body); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); }); }, DeleteSetting: function (req, res) { console.log('Data Record', req.body); jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.id == req.params.id); }); index = obj.indexOf(index[0]); console.log('Index Of Record', index); if (index > -1) { obj.splice(index, 1); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } else { res.json(obj); } }); }, UpdateSetting: function (req, res) { jFile.readFile(filePath, function (err, obj) { console.log(req.body.id) index = obj.filter(function (item) { return (item.id == req.body.id); }); index = obj.indexOf(index[0]); if (index > -1) { obj[index] = req.body; jFile.writeFile(filePath, obj, {}, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } }); }, GetActiveSetting: function (cb) { jFile.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); return cb(obj.filter(m=>m.status=="Active")); }); } } module.exports = Setting;<file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/map"; @Injectable() export class DailyTranService { constructor(private http: Http) {} GetDailyTran(){ return this.http.get("/api/dailytran").map(res=>res.json()); } SaveDailyTran(data){ return this.http.post("/api/dailytran",data).map(res=>res.json()); } UpdateDaily(data){ return this.http.put("/api/dailytran/"+data.id,data).map(res=>res.json()); } DeleteDaily(data){ return this.http.delete("/api/dailytran/"+data.id,data).map(res=>res.json()); } } <file_sep>import { Component, EventEmitter, Output} from '@angular/core'; import { DailyTranService} from '../../Services/daily.service'; import { Router, ActivatedRoute} from '@angular/router'; import { UUID } from 'angular2-uuid'; import { Sorter} from '../../Services/app.sort'; import swal from 'sweetalert2'; @Component({ selector: 'app-dailytran', templateUrl: './dailytran.component.html', providers: [DailyTranService,Sorter] }) export class DailyTranComponent { oSetting: any; Settings: any[]; prev:number=-1; cols:any[]=[ { name:"receiveTime", title:"Receive Time", sorted:false, sortAs:"", sortable:true }, { name:"fileName", title:"File Name", sorted:false, sortAs:"", sortable:true }, { name:"client", title:"Client", sorted:false, sortAs:"", sortable:true }, { name:"records.length", title:"Total/New", sorted:false, sortAs:"", sortable:true }, { name:"", title:"Action", sorted:false, sortAs:"" , sortable:false } ]; IsNew:boolean=false; selectedRow:number; firstNameFilter:string; HideCross:boolean=true; constructor(private _route: ActivatedRoute, private _router: Router, private userService: DailyTranService,private sortService:Sorter) { userService.GetDailyTran().subscribe(m => { this.Settings = m; this.sortService.direction=1; this.sortService.sort(this.cols[0],this.Settings); }); } onEdit(obj,i) { this.selectedRow=i; this.oSetting = Object.assign({}, obj); // obj; } showNew(data){ this.IsNew=data; } getNew(records) { return records.filter(m=>m.IsNew==true).length; } SortColumn(key) { this.sortService.sort(key,this.Settings); } showCross() { if(this.firstNameFilter.length>0) this. HideCross=false; else this.HideCross=true; } onRemove() { this. HideCross=true; this.firstNameFilter=""; } } <file_sep>// jobs.js var setting = require('../Service/setting.js'); var Daily = require('../Service/daily.js'); var CountryDB = require('../Service/country.js'); var XML = require('../Service/xmllog.js'); var XMLService = require('./xml.job.service.js'); var path = require('path'); var nodemailer = require('nodemailer'); var dateFormat = require('dateformat'); var moment = require('moment'); var fs = require('fs'); var config = require('config'); exports.CheckNewFiles = { after: { // Configuring this job to run after this period. seconds: 10, minutes: 0, hours: 0, days: 0 }, job: function () { // Get All Active Setting setting.GetActiveSetting(function (data) { // loop through all the setting and Read Data for Source Location try { if (data.length > 0) CallSettingOneByOne(data, 0); } catch (ex) { console.log("Error", ex); } }); }, spawn: true } exports.PurgeArchiveData = { after: { // Configuring this job to run after this period. seconds: 300, minutes: 0, hours: 0, days: 0 }, // Cron tab instruction. job: function () { setting.GetActiveSetting(function (data) { // loop through all the setting and Read Data for Source Location try { if (data.length > 0) DeleteArchiveOneByOne(data, 0); } catch (ex) { console.log("Error", ex); } }); }, spawn: false // If false, the job will not run in a separate process. } // This is not a Job /*var CountryExcel= { RunCountry: function () { ProcessCountryExcel(); } } module.exports =CountryExcel; */ function RemoveAll(data, item) { for (var i = data.length - 1; i--;) { if (data[i].PO === item) data.splice(i, 1); } return data; } function CallSettingOneByOne(Data, SettingIndex) { var Setting = Data[SettingIndex]; var SourceFile = Setting.sourceFile + "\\" + Setting.fullFileName; var SourceFileShip = Setting.sourceFile + "\\" + Setting.halfFileName; ProcessFile(SourceFile, Setting, "f", function () { ProcessFile(SourceFileShip, Setting, "h", function (data) { SettingIndex++; if (Data[SettingIndex] != undefined) CallSettingOneByOne(Data, SettingIndex); }); // helf }); //full } function GetXMLFileName(Setting, fileobj) { var FileName = ""; if (Setting.fullFileName == fileobj.base) { if (Setting.combinefullFile == "") { FileName = fileobj.name + "_" + dateFormat(Date.now(), 'yyyymmddhhMM') + ".xml"; } else { FileName = path.parse(Setting.combinefullFile).base + "_" + dateFormat(Date.now(), 'yyyymmddhhMM') + ".xml"; } } else { if (Setting.combinehalfFile == "") { FileName = fileobj.name + "_" + dateFormat(Date.now(), 'yyyymmddhhMM') + ".xml"; } else { FileName = path.parse(Setting.combinehalfFile).base + "_" + dateFormat(Date.now(), 'yyyymmddhhMM') + ".xml"; } } // console.log("File name", FileName); return FileName; } function ProcessFile(SourceFile, Setting, type, cb) { var AppSetting = config.get("Application"); if (fs.existsSync(SourceFile)) { // console.log("Next Read Excel"); XMLService.ReadExcel(SourceFile, Setting.clientName, function (ExcelJson) { // console.log("Excel", ExcelJson); var fData = path.parse(SourceFile); Daily.XMLRecordExistMultiple(ExcelJson, function (JsonRecord) { // console.log("Total New Record", JsonRecord.length); if (JsonRecord.length == 0) { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; fs.renameSync(SourceFile, DailyArchive); // Daily Archiving Daily.SaveDaily(ExcelJson, fData.base, DailyArchive, Setting.clientName, function () { }); // Send Error Email Stating that there is error in Source file unable to process. var msg = "Hi,\n\n"; msg += " The file " + fData.base + " has found following :\n\n"; msg += " No new record found \n\n"; msg += "\nFile process action is aborted. \n"; msg += "Correct the error in the file or recreate the file \n"; msg += "Drop the file at Source location : " + Setting.sourceFile + " \n"; msg += "\nEDI-XML Team \n"; msg += "RS RUSH \n"; SendLogEmail(Setting.userEmail, "XML files processing :" + dateFormat(Date.now(), 'yyyy-mm-dd hh:MM'), msg); cb("Done With Errors"); } else { XMLService.GroupByJsonData(JsonRecord, function (GRecord) { var TotalGRecord = GRecord.length; var ProcessGRecord = 0; var CombineXML = ""; var CombineLog = []; var xmlCol = []; // console.log("GRecod out Foreach"); GRecord.forEach(function (Record) { // console.log("GRecod in Foreach", Record.Records.length); XMLService.CreateXML(Record.Records, Setting.clientName, type == "f" ? true : false, function (xmlData) { // console.log("XML Creation"); batchNumber = Date.now(); ProcessGRecord++; // console.log("Total ProcessGRecord " + ProcessGRecord, TotalGRecord); CombineXML += xmlData.xml; if (xmlData.xml != "") { // Only Add if Successfully created XML without any error(s) xmlData.ID = Record.ID; xmlCol.push(xmlData); } if (CombineLog.length == 0) CombineLog = xmlData.log; else CombineLog = CombineLog.concat(xmlData.log); console.log("Current Log %d Total Log %d", xmlData.log.length, CombineLog.length); if (TotalGRecord == ProcessGRecord) // Upload { // console.log("", xmlCol.filter(m => m.xml.length == 0).length); /* if (combineXML==) { if (xmlData.msg == "No new record found") { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; fs.renameSync(SourceFile, DailyArchive); // Daily Archiving Daily.SaveDaily(JsonRecord, fData.base, DailyArchive, Setting.clientName, function () { }); } else { if (fs.existsSync(SourceFile)) { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_Error_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; fs.renameSync(SourceFile, DailyArchive); } // Daily Archiving } // Send Error Email Stating that there is error in Source file unable to process. var msg = "Hi,\n\n"; msg += " The file " + fData.base + " has found following error:\n\n"; msg += " Error: " + xmlData.msg + "\n\n"; msg += "\nFile process action is aborted. \n"; msg += "Correct the error in the file or recreate the file \n"; msg += "Drop the file at Source location : " + Setting.sourceFile + " \n"; msg += "\nEDI-XML Team \n"; msg += "RS RUSH \n"; SendLogEmail(Setting.userEmail, "XML files Processing error :" + dateFormat(Date.now(), 'yyyy-mm-dd hh:MM'), msg); cb("Done With Errors"); } else {*/ if (Setting.combineXML == "Yes") { if (CombineXML == "") { if (Setting.sendEmail === "1") { EmailToUser("", Setting.userEmail, AppSetting, fData, JsonRecord); } // console.log("Saved XML ", FileName); cb("Done"); } else { FileName = GetXMLFileName(Setting, fData); var XMLString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?> <scp_edistatusqueue>" + CombineXML + "</scp_edistatusqueue>"; XMLService.UploadToFtp(Setting.serverName, Setting.userName, Setting.password, Setting.endPoint + "/" + FileName, XMLString, function (ftpInfo) { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; if (fs.existsSync(SourceFile)) fs.renameSync(SourceFile, DailyArchive); // Daily Archiving Daily.SaveDaily(JsonRecord, fData.base, DailyArchive, Setting.clientName, function () { var ShipmentNumber = Setting.xmlFile + "\\" + FileName; fs.appendFileSync(ShipmentNumber, XMLString); // Archiving XML file if (Setting.sendEmail === "1") { var msg = "Hi,\n\n"; msg += " Incoming file :" + fData.base + "\n\n"; msg += " The following XMLs has been send send successfully:\n\n"; msg += FileName + " " + ftpInfo + "\n\n"; msg += "\nFor complete history or more details : " + AppSetting.AppUrl + " \n"; msg += "\nEDI-XML Team \n"; msg += "RS RUSH \n"; SendLogEmail(Setting.clientEmail, "XML file has (" + xmlCol.length + ") records successfully send :" + dateFormat(Date.now(), 'yyyy-mm-dd hh:MM'), msg); EmailToUser(FileName + " " + ftpInfo + "\n\n", Setting.userEmail, AppSetting, fData, JsonRecord); } XML.SaveXmlLog(CombineLog, FileName, ShipmentNumber, Setting.id, batchNumber, Setting.clientName, function (data) { // console.log("Saved XML ", FileName); cb("Done"); }); }); // Save Daily Reacords }); // ftp Upload } } // Combine End else { // console.log("Single File", xmlCol.length); if (xmlCol.length == 0) { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; if (fs.existsSync(SourceFile)) fs.renameSync(SourceFile, DailyArchive); // Daily Archiving if (Setting.sendEmail === "1") { // EmailToUser("", Setting.userEmail, JsonRecord); Daily.SaveDaily(ExcelJson, fData.base, DailyArchive, Setting.clientName, function () { EmailToUser("", Setting.userEmail, AppSetting, fData, JsonRecord); }); } // console.log("Saved XML ", FileName); cb("Done"); } else { var TotalS = xmlCol.length; var PS = 0; var FileNames = ""; var files = ""; xmlCol.forEach(function (Item) { var FileName = Item.ID + "_" + dateFormat(Date.now(), 'yyyymmddhhMM') + ".xml"; var XMLString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?> <scp_edistatusqueue>" + Item.xml + "</scp_edistatusqueue>"; XMLService.UploadToFtp(Setting.serverName, Setting.userName, Setting.password, Setting.endPoint + "/" + FileName, XMLString, function (ftpInfo) { var DailyArchive = Setting.dailyLog + "\\" + fData.name + "_" + dateFormat(Date.now(), "yyyymmddhhMM") + fData.ext; if (fs.existsSync(SourceFile)) fs.renameSync(SourceFile, DailyArchive); // Daily Archiving var ShipmentNumber = Setting.xmlFile + "\\" + FileName; fs.appendFileSync(ShipmentNumber, XMLString); // Archiving XML file XML.SaveXmlLog(Item.log, FileName, ShipmentNumber, Setting.id, batchNumber, Setting.clientName, function (data) { // console.log("Saved XML ", FileName); files += FileName + " " + ftpInfo + "\n"; PS++; if (TotalS == PS) { Daily.SaveDaily(ExcelJson, fData.base, DailyArchive, Setting.clientName, function () { cb("Done"); if (Setting.sendEmail === "1") { var msg = "Hi,\n\n"; msg += " Incoming file :" + fData.base + "\n\n"; msg += " The following XMLs has been send send successfully:\n\n"; msg += files + "\n"; msg += "\nFor complete history or more details : " + AppSetting.AppUrl + " \n"; msg += "\nEDI-XML Team \n"; msg += "RS RUSH \n"; SendLogEmail(Setting.clientEmail, "XML files (" + xmlCol.length + ") successfully send :" + dateFormat(Date.now(), 'yyyy-mm-dd hh:MM'), msg); EmailToUser(files, Setting.userEmail, AppSetting, fData, JsonRecord); } }); // Daily } }); }); // ftp Upload }) } } // } // Let Process All Records } }); // Create XML }); // Group Data One By One }); // Group By PO } // else Has new Records }) // Reach IsNew Multiple }); // Read Exl } else { cb("data"); } } function EmailToUser(Sucessfullmsg, ToEmailAddress, AppSetting, fData, JsonData) { var error = ""; for (i = 0; i < JsonData.length; i++) { m = JsonData[i]; if (m.Error == true) { error += " Record No :" + m.RecordNo + " PO Number :" + m.PO + " Error :" + m.ErrorMsg + "\n"; } } var msg = "Hi,\n\n"; msg += " Incoming file :" + fData.base + "\n\n"; msg += " The following XMLs has been send send successfully:\n\n"; msg += Sucessfullmsg + "\n\n"; msg += " The following transcation records has erros while processing: \n\n"; msg += error + "\n\n"; msg += "\nFor complete history or more details : " + AppSetting.AppUrl + " \n"; msg += "\nEDI-XML Team \n"; msg += "RS RUSH \n"; SendLogEmail(ToEmailAddress, "XML files processing status :" + dateFormat(Date.now(), 'yyyy-mm-dd hh:MM'), msg); } function SendLogEmail(to, subject, body) { var EmailConfig = config.get("EmailServer"); /* var transporter = nodemailer.createTransport({ service: EmailConfig.host, auth: { user: EmailConfig.username, pass: <PASSWORD> } }); */ var transporter = nodemailer.createTransport({ host: EmailConfig.host, // hostname secureConnection: false, // TLS requires secureConnection to be false port: EmailConfig.port, // port for secure SMTP auth: { user: EmailConfig.username, pass: <PASSWORD> }, tls: { ciphers: 'SSLv3' } }); var mailOptions = { from: EmailConfig.from, to: to, subject: subject, text: body }; transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); } // Delete Archive Records // Step 1 function DeleteArchiveOneByOne(Data, SettingIndex) { var Setting = Data[SettingIndex]; var DailyDays = Setting.dailyArchive; var XmlDays = Setting.xmlHistory; DeleteDailyArchive(DailyDays, function () { DeleteXMLHistory(XmlDays, function (data) { SettingIndex++; if (Data[SettingIndex] != undefined) DeleteArchiveOneByOne(Data, SettingIndex); }); // helf }); //full } // Delete Daily Log Entries and Files function DeleteDailyArchive(Days, cb) { var date = moment().subtract(Days, 'days').format('X'); // console.log(date, " ", moment().format('X')); Daily.GetArchiveRecord(date, function (list) { list.forEach(function (oDelRecord) { if (fs.existsSync(oDelRecord.logFile)) { fs.unlinkSync(oDelRecord.logFile); } }) Daily.DeleteAndUpdate(list, function () { // console.log("Daily Done LA Removed"); cb(" Daily Archived File Removed"); }) }); } function DeleteXMLHistory(Days, cb) { var date = moment().subtract(Days, 'days').format('X'); // console.log(date, " ", moment().format('X')); XML.GetArchiveRecord(date, function (list) { list.forEach(function (oDelRecord) { if (fs.existsSync(oDelRecord.logFile)) { fs.unlinkSync(oDelRecord.logFile); } }) XML.DeleteAndUpdate(list, function () { // console.log("XML Done LA Removed"); cb("Archived File Removed"); }) }); }<file_sep>var jFile = require('jsonfile'); var filePath = './DataDB/freight.json'; var Freight = { GetFreight: function (req, res) { jFile.readFile(filePath, function (err, obj) { if (err) console.log("Error", err); res.json(obj) }); }, SaveFreight: function (req, res) { console.log("Data ", req.body) // spoofing the DB response for simplicity jFile.readFile(filePath, function (err, obj) { obj.push(req.body); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); }); }, DeleteFreight: function (req, res) { console.log('Data Record', req.body); jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.id == req.params.id); }); index = obj.indexOf(index[0]); console.log('Index Of Record', index); if (index > -1) { obj.splice(index, 1); jFile.writeFile(filePath, obj, { }, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } else { res.json(obj); } }); }, UpdateFreight: function (req, res) { jFile.readFile(filePath, function (err, obj) { console.log(req.body.id) index = obj.filter(function (item) { return (item.id == req.body.id); }); index = obj.indexOf(index[0]); if (index > -1) { obj[index] = req.body; jFile.writeFile(filePath, obj, {}, function (err) { console.error("rror", err); if (err == null) res.json(obj); }); } }); }, GetStatusAndLocDB: function (TType, TDirection, Freight,ShipType, cb) { jFile.readFile(filePath, function (err, obj) { index = obj.filter(function (item) { return (item.ttype.toString().toLowerCase() == TType.toString().toLowerCase() && item.tdirection.toString().toLowerCase() == TDirection.toString().toLowerCase() && item.shiptype.toString().toLowerCase() == ShipType.toString().toLowerCase() && item.fcode.toString().toLowerCase() == Freight.toString().toLowerCase()); }); console.log(index); if (index.length > 0) cb(index[0]); else cb(null); }); } } module.exports = Freight;<file_sep>import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import {CommonModule} from '@angular/common'; import { HttpModule } from '@angular/http'; import { RouterModule} from '@angular/router'; import { SettingsComponent} from './settings.component'; import { Ng2PaginationModule} from 'ng2-pagination'; import { SettingsFilterPipe } from './settings.filter'; @NgModule({ declarations: [ SettingsComponent, SettingsFilterPipe ], imports: [ FormsModule, CommonModule, HttpModule, Ng2PaginationModule, RouterModule.forRoot([ {path:'settings',component:SettingsComponent} ]), RouterModule ], providers: [], }) export class SettingsdModule { } <file_sep>import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import {CommonModule} from '@angular/common'; import { HttpModule } from '@angular/http'; import { RouterModule} from '@angular/router'; import { ChartsModule } from 'ng2-charts/ng2-charts'; import { DashboardComponent } from './dashboard.component'; import { BasicChartReport } from '../chart/chart.base.component'; @NgModule({ declarations: [ DashboardComponent, BasicChartReport ], imports: [ FormsModule, CommonModule, HttpModule, ChartsModule, RouterModule.forRoot([ {path:'dashboard',component:DashboardComponent} ]), RouterModule ], providers: [], }) export class DashboardModule { } <file_sep>import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import {CommonModule} from '@angular/common'; import { HttpModule } from '@angular/http'; import { RouterModule} from '@angular/router'; import { FreightComponent} from './freight.component'; import { Ng2PaginationModule} from 'ng2-pagination'; import { FreightFilterPipe } from './freight.filter'; @NgModule({ declarations: [ FreightComponent, FreightFilterPipe ], imports: [ FormsModule, CommonModule, HttpModule, Ng2PaginationModule, RouterModule.forRoot([ {path:'freightscode',component:FreightComponent} ]), RouterModule ], providers: [], }) export class FreightModule { } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { RouterModule} from '@angular/router'; import { LoginComponent } from './login/login.component'; import { MasterComponent } from './master/master.component'; import { DashboardModule } from './dashboard/dashboard.module'; import { SettingdModule } from './setting/setting.module'; import { SettingsdModule } from './settings/settings.module'; import { UserModule } from './user/user.module'; import { FreightModule } from './freight/freight.module'; import { DailyTranModule } from './dailytran/dailytran.module'; import { XmlLogModule } from './xmllog/xmllog.module'; import { CountryModule } from './country/country.module'; @NgModule({ declarations: [ AppComponent, LoginComponent, MasterComponent ], imports: [ BrowserModule, DashboardModule, SettingdModule, SettingsdModule, FormsModule, UserModule, FreightModule, DailyTranModule, XmlLogModule, CountryModule, HttpModule, RouterModule.forRoot([ ]), RouterModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, EventEmitter, Output } from '@angular/core'; import { XmlLognService } from '../../Services/xmllog.service'; import { Sorter } from '../../Services/app.sort'; import { Router, ActivatedRoute } from '@angular/router'; import { UUID } from 'angular2-uuid'; import swal from 'sweetalert2'; @Component({ selector: 'app-xmllog', templateUrl: './xmllog.component.html', providers: [XmlLognService, Sorter] }) export class XmlLogComponent { oSetting: any; Settings: any[]; prev: number = -1; IsNew:boolean=false; cols: any[] = [{ name: "batchid", title: "Batch #", sorted: true, sortAs: "", sortable: true }, { name: "fileName", title: "File Name", sorted: false, sortAs: "", sortable: true }, { name: "client", title: "Client", sorted: false, sortAs: "", sortable: true }, { name: "receiveTime", title: "Created Time", sorted: false, sortAs: "", sortable: true }, { name: "records.length", title: "No of Records", sorted: false, sortAs: "", sortable: true }, { name: "", title: "Action", sorted: false, sortAs: "", sortable: false } ]; selectedRow: number; firstNameFilter: string; HideCross: boolean = true; constructor(private _route: ActivatedRoute, private _router: Router, private userService: XmlLognService, private sortService: Sorter) { userService.GetXmlLog().subscribe(m => { this.Settings = m; this.sortService.direction = 1; this.sortService.sort(this.cols[3], this.Settings); }); } getNew(records) { return records.filter(m=>m.IsNew==true).length; } onEdit(obj, i) { this.selectedRow = i; this.oSetting = Object.assign({}, obj); // obj; } showNew(data){ this.IsNew=data; } showCross() { if (this.firstNameFilter.length > 0) this.HideCross = false; else this.HideCross = true; } SortColumn(key) { this.sortService.sort(key, this.Settings); } onRemove() { this.HideCross = true; this.firstNameFilter = ""; } reSend(id, event) { this.userService.ResendB(id).subscribe(m => { swal('Success', 'XMLs resended successfully..', 'success'); }); } Single(id, event) { if (event == "cancel") { this.userService.Resend(id).subscribe(m => { swal('Success', 'XML resended successfully..', 'success'); }); } } } <file_sep>var Client = require('ftp'); var nodemailer = require('nodemailer'); var fs = require('fs'); var XLSX = require('xlsx'); var uuidV1 = require('uuid/v1'); var FreighService = require('../Service/freight.js'); var CountryService = require('../Service/country.js'); var config = require('config'); var moment = require('moment'); var XMLService = { SendEmail: function () { }, GroupByJsonData: function (InputData, cb) { var GroupData = []; InputData.forEach(function (Item) { var HaveItem = []; if (GroupData.length > 0) HaveItem = GroupData.filter(m => m.ID == Item.PO); else HaveItem = []; if (HaveItem.length == 0) { GroupData.push({ "ID": Item.PO, "Records": InputData.filter(m => m.PO == Item.PO) }); } }); // console.log("G Data", GroupData); cb(GroupData); }, ReadExcel: function (InputFile, Client, cb) { var workbook = XLSX.readFile(InputFile); var dataRows = []; var row = 2; var SheetName = workbook.SheetNames[0]; while (GetData(workbook, SheetName, "A" + row) != "") { try { //console.log("Daa",workbook.Sheets.A["Q"+ row]) dataRows.push( { "ID": GetData(workbook, SheetName, "A" + row), "Origin": GetData(workbook, SheetName, "B" + row), "Destination": GetData(workbook, SheetName, "C" + row), "BOL": GetData(workbook, SheetName, "D" + row), "PO": GetData(workbook, SheetName, "E" + row), "TraceCd": GetData(workbook, SheetName, "F" + row), "Freight": GetData(workbook, SheetName, "G" + row), "Finance": GetData(workbook, SheetName, "H" + row), "ShipType": GetData(workbook, SheetName, "I" + row), "Customer": GetData(workbook, SheetName, "J" + row), "Shipper": GetData(workbook, SheetName, "K" + row), "Consignee": GetData(workbook, SheetName, "L" + row), "Note": GetData(workbook, SheetName, "M" + row), "ContainerNumber": GetData(workbook, SheetName, "N" + row), "TType": GetData(workbook, SheetName, "O" + row), "TDirection": GetData(workbook, SheetName, "P" + row), "Date": GetData(workbook, SheetName, "Q" + row), "Time": GetData(workbook, SheetName, "R" + row), "UNCODE": GetData(workbook, SheetName, "S" + row), "Client": Client, "RecordNo": row, "Error": false, "ErrorMsg": "" }); // dataRows.push(row); } catch (ex) {} row = row + 1; } console.log("Total Excel Reocrds",dataRows); cb(dataRows); }, CreateXML: function (JsonData, Client, isuFile, cb) { var interXML = ""; var TotalRecord = JsonData.length; var Processed = 0; var logData = []; var Application = config.get("Application"); JsonData.forEach(function (item) { // for (i = 0; i < JsonData.length; i++) { // item = JsonData[i]; FreighService.GetStatusAndLocDB(item.TType, item.TDirection, item.Freight, item.ShipType, function (data) { //console.log("Date", moment(new Date(item.Date)).format("YYYY-MM-DD")); var country = "CA"; var locName; var subdiv; if (data != null) { //if (data.length > 0) { if (data.floc.toString().toLowerCase() == "origin") { if (item.Origin.split(',').length > 0) { locName = item.Origin.split(',')[0].trim(); subdiv = item.Origin.split(',')[1].trim(); } else { locName = item.Origin.toString().trim(); subdiv = ""; //item.Origin.split(',')[1].trim(); } } else { if (item.Destination.split(',').length > 0) { locName = item.Destination.split(',')[0].trim(); subdiv = item.Destination.split(',')[1].trim(); } else { locName = item.Destination.toString().trim(); subdiv = ""; //item.Origin.split(',')[1].trim(); } } CountryService.GetUnCode(country, locName, subdiv, function (unCode) { if (unCode == null) { Processed++; unCode = {}; unCode.COUNTRY = "CA"; unCode.UNCODE = ""; /* cb({ "xml": "", "log": [], "msg": "Unable to find stsloccd" });*/ item.Error = true; item.ErrorMsg = "Unable to find stsloccd"; // console.log("processed %d Total %d", Processed, TotalRecord, item); if (Processed == TotalRecord) { if (interXML == "") { cb({ "xml": interXML, "log": logData, "msg": "No new record found" }); } else { cb({ "xml": interXML, "log": logData, "msg": "" }); } } } else { Processed++; if (isuFile == false) { if (item.IsNew) { interXML += "<Scp_edistatusqueue><messagesdr>" + Application.OwnerName + "</messagesdr>" + "<shipnum>" + item.PO + "</shipnum> " + "<statuscd>" + data.scode + "</statuscd>" + "<statusdt>" + moment(new Date(item.Date)).format("YYYY-MM-DD") + " " + item.Time + "</statusdt>" + "<stsloccd>" + unCode.COUNTRY + unCode.UNCODE + "</stsloccd></Scp_edistatusqueue>"; } logData.push({ "messagesdr": Application.OwnerName, "shipnum": item.PO, "statuscd": data.scode, "statusdt": moment(new Date(item.Date)).format("YYYY-MM-DD") + " " + item.Time, "stsloccd": unCode.COUNTRY + unCode.UNCODE, "ufileid": "", "contno": "", "IsNew": item.IsNew }); } else { if (item.IsNew) { interXML += "<Scp_edistatusqueue><messagesdr>" + Application.OwnerName + "</messagesdr>" + "<ufileid>" + item.PO + "</ufileid><contno>" + item.TraceCd + "</contno>" + "<statuscd>" + data.scode + "</statuscd>" + "<statusdt>" + moment(new Date(item.Date)).format("YYYY-MM-DD") + " " + item.Time + "</statusdt>" + "<stsloccd>" + unCode.COUNTRY + unCode.UNCODE + "</stsloccd></Scp_edistatusqueue>"; logData.push({ "messagesdr": Application.OwnerName, "shipnum": "", "statuscd": data.scode, "statusdt": moment(new Date(item.Date)).format("YYYY-MM-DD") + " " + item.Time, "stsloccd": unCode.COUNTRY + unCode.UNCODE, "ufileid": item.PO, "contno": item.TraceCd, "IsNew": item.IsNew }); } } // console.log("processed %d Total %d", Processed, TotalRecord, item); if (Processed == TotalRecord) { if (interXML == "") { cb({ "xml": interXML, "log": logData, "msg": "No new record found" }); } else { cb({ "xml": interXML, "log": logData, "msg": "" }); } } } }); // UnCode } else { Processed++; item.Error = true; item.ErrorMsg = "Unable to find statuscd"; /* cb({ "xml": "", "log": [], "msg": "Unable to find statuscd" }); return;*/ console.log("processed %d Total %d", Processed, TotalRecord, item); if (Processed == TotalRecord) { if (interXML == "") { cb({ "xml": interXML, "log": logData, "msg": "No new record found" }); } else { cb({ "xml": interXML, "log": logData, "msg": "" }); } } } }); }); }, UploadToFtp(Host, userName, Password, fileName, content, cb) { var c = new Client(); c.on('ready', function () { c.put(content, fileName, function (err) { if (err) console.log("ftp error" + err); c.end(); cb("ok"); }); }); c.on('error', function (err) { console.log("ftp error", err); cb("error unable to connect to ftp server"); }); // connect to localhost:21 as anonymous c.connect({ host: Host, user: userName, password: <PASSWORD> }); } } function GetData(obj, SheetName, col) { try { if(col.toString().indexOf('R')==0) return moment(new Date("2017-10-10 "+obj.Sheets[SheetName][col].w.trim())).format("HH:mm:ss"); else return obj.Sheets[SheetName][col].w; //obj.Sheets[SheetName][col].w; } catch (ex) { return ""; } } module.exports = XMLService;<file_sep>import { Component ,EventEmitter,Output} from '@angular/core'; import { AppGlobals} from '../../Services/app.global'; import { Router, ActivatedRoute} from '@angular/router'; import { UserService} from '../../Services/user.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styles: ['./login.css'], providers: [AppGlobals,UserService] }) export class LoginComponent { LogMessage:string; userName:string; password:string; @Output() CheckLogin= new EventEmitter<boolean>(); constructor(private appG: AppGlobals, private _route: ActivatedRoute, private _router: Router,private logSer:UserService) { this.LogMessage=""; } LoginMe() { this.logSer.Login({userName:this.userName,password:<PASSWORD>}).subscribe(m=>{ if(m.status==true) { this.appG.SetToken(m.user.userName); this.appG.SetUser(m.user); this.CheckLogin.emit(true); } else { this.LogMessage="Login name or password is invalid.."; } }); } } <file_sep>import { Component, EventEmitter, Output} from '@angular/core'; import { SettingService} from '../../Services/setting.service'; import { Sorter} from '../../Services/app.sort'; import { Router, ActivatedRoute} from '@angular/router'; import { Valid, ValidateMe, ValidateMeRule} from '../shared/app.helper'; import { UUID} from 'angular2-uuid'; import swal from 'sweetalert2'; @Component({ selector: 'app-setting', templateUrl: './setting.component.html', providers: [SettingService,Sorter] }) export class SettingComponent { oSetting: any; Settings: any[]; prev:number=-1; cols:any[]=[ { name:"serverName", title:"URL", sorted:false, sortAs:"", sortable:true }, { name:"clientName", title:" Client Name", sorted:false, sortAs:"", sortable:true }, { name:"endPoint", title:"End Point", sorted:false, sortAs:"", sortable:true }, { name:"sourceFile", title:"Source File", sorted:false, sortAs:"", sortable:true }, { name:"status", title:"Status", sortAs:"", sortable:false } , { name:"", title:"Action", sorted:false, sortAs:"", sortable:false } ]; selectedRow:number; firstNameFilter:string; HideCross:boolean=true; constructor(private _route: ActivatedRoute, private _router: Router, private settingService: SettingService , private sortService:Sorter) { settingService.GetSetting().subscribe(m => { this.Settings = m; }); } onEdit(obj,i) { this.selectedRow=i; this.oSetting = Object.assign({}, obj); // obj; } onDel(obj) { this.settingService.DeleteSetting(obj).subscribe(m => { swal('Success', 'Setting deleted successfully...', 'success'); this.Settings = m; this.onNew(); }); } showCross() { if(this.firstNameFilter.length>0) this. HideCross=false; else this.HideCross=true; } SortColumn(key) { this.sortService.sort(key,this.Settings); } onRemove() { this. HideCross=true; this.firstNameFilter=""; } onNew() { this.selectedRow=-1; this.oSetting = { "id": "", "serviceType": '', "clientName": "", "serverName": "", "endPoint": "", "userName": "", "password": "", "interval": 0, "status": '', "sourceFile": "", "dailyLog": "", "xmlFile": "", "compareFile": '', "dailyArchive": 0, "xmlHistory": 0 } ValidateMe("#SettingForm"); } Save() { if (Valid("#SettingForm")) { if (this.oSetting.id != "") { this.settingService.UpdateSetting(this.oSetting).subscribe(m => { swal('Success', 'Setting updated successfully...', 'success'); this.Settings = m; this.onNew(); }); } else { this.oSetting.id = UUID.UUID(); this.settingService.SaveSetting(this.oSetting).subscribe(m => { swal('Success', 'Setting added successfully...', 'success'); this.Settings = m; this.onNew(); }); } } } } <file_sep>import { Component, EventEmitter, Output } from '@angular/core'; import { CountryService } from '../../Services/country.service'; import { Router, ActivatedRoute } from '@angular/router'; import { UUID } from 'angular2-uuid'; import swal from 'sweetalert2'; import { FileUploader } from 'ng2-file-upload'; import { Sorter } from '../../Services/app.sort'; @Component({ selector: 'app-country', templateUrl: './country.component.html', providers: [CountryService, Sorter] }) export class CountryComponent { oSetting: any; Settings: any[]; prev: number = -1; cols: any[] = [ { name: "COUNTRY", title: "COUNTRY", sorted: false, sortAs: "", sortable: true }, { name: "UNCODE", title: "UNCODE", sorted: false, sortAs: "", sortable: true }, { name: "LOCNAME", title: "LOCNAME", sorted: false, sortAs: "", sortable: true }, { name: "SUBDIV", title: "SUBDIV", sorted: false, sortAs: "", sortable: true }, { name: "IATACODE", title: "IATA CODE", sorted: false, sortAs: "", sortable: true } , { name: "IATANAME", title: "IATA NAME", sorted: false, sortAs: "", sortable: true } , { name: "TIMEXONE", title: "TIME ZONE", sorted: false, sortAs: "", sortable: true }, { name: "PORT", title: "PORT", sorted: false, sortAs: "", sortable: true }, { name: "AIRPORT", title: "AIRPORT", sorted: false, sortAs: "", sortable: true }, { name: "RAIL", title: "RAIL", sorted: false, sortAs: "", sortable: true }, { name: "ROAD", title: "ROAD", sorted: false, sortAs: "", sortable: true } , { name: "UNSTANDARD", title: "UNSTANDARD", sorted: false, sortAs: "", sortable: true }, { name: "LOCALNAME", title: "LOCALNAME", sorted: false, sortAs: "", sortable: true }, { name: "NONIATA", title: "NON IATA", sorted: false, sortAs: "", sortable: true } , { name: "VALIDFROM", title: "VALID FROM", sorted: false, sortAs: "", sortable: true }, { name: "VALIDTO", title: "VALID TO", sorted: false, sortAs: "", sortable: true } ]; public hasBaseDropZoneOver: boolean = false; selectedRow: number; firstNameFilter: string; HideCross: boolean = true; public uploader: FileUploader = new FileUploader({ url: '/fileupload' }); constructor(private _route: ActivatedRoute, private _router: Router, private userService: CountryService, private sortService: Sorter) { userService.GetCountry().subscribe(m => { this.Settings = m; }); } public fileOverBase(e: any): void { this.hasBaseDropZoneOver = e; } onEdit(obj, i) { this.selectedRow = i; this.oSetting = Object.assign({}, obj); // obj; } SortColumn(key) { this.sortService.sort(key, this.Settings); } showCross() { if (this.firstNameFilter.length > 0) this.HideCross = false; else this.HideCross = true; } onRemove() { this.HideCross = true; this.firstNameFilter = ""; } } <file_sep>import { Component, EventEmitter, Output} from '@angular/core'; import { UserService} from '../../Services/user.service'; import { Sorter} from '../../Services/app.sort'; import { ValidateMe, Valid} from '../shared/app.helper'; import { Router, ActivatedRoute} from '@angular/router'; import { UUID} from 'angular2-uuid'; import swal from 'sweetalert2'; @Component({ selector: 'app-user', templateUrl: './user.component.html', providers: [UserService,Sorter] }) export class UserComponent { oSetting: any; Settings: any[]; prev:number=-1; cols:any[]=[ { name:"userName", title:"<NAME>", sorted:false, sortAs:"", sortable:true }, { name:"firstName", title:"<NAME>", sorted:false, sortAs:"", sortable:true }, { name:"lastName", title:"<NAME>", sorted:false, sortAs:"", sortable:true }, { name:"role", title:"Role", sorted:false, sortAs:"", sortable:true }, { name:"status", title:"Status", sorted:false, sortAs:"" , sortable:false } , { name:"", title:"Action", sorted:false, sortAs:"" , sortable:false } ]; selectedRow: number; firstNameFilter: string; HideCross: boolean = true; constructor(private _route: ActivatedRoute, private _router: Router, private userService: UserService,private sortService:Sorter) { userService.GetUser().subscribe(m => { this.Settings = m; this.sortService.sort(this.cols[0],this.Settings); }); } showCross() { if (this.firstNameFilter.length > 0) this.HideCross = false; else this.HideCross = true; } SortColumn(key) { this.sortService.sort(key,this.Settings); } onRemove() { this.HideCross = true; this.firstNameFilter = ""; } onEdit(obj, i) { this.selectedRow = i; this.oSetting = Object.assign({}, obj); // obj; } onDel(obj) { this.userService.DeleteUser(obj).subscribe(m => { swal('Success', 'User deleted successfully...', 'success'); this.Settings = m; this.onNew(); }); } onNew() { this.selectedRow = -1; this.oSetting = { "id": "", "role": 0, "firstName": "", "lastName": "", "userName": "", "password": "", "status": true } ValidateMe("#myForm"); } Save() { if (Valid("#myForm")) { if (this.oSetting.id != "") { this.userService.UpdateUser(this.oSetting).subscribe(m => { swal('Success', 'User updated successfully...', 'success'); this.Settings = m; this.onNew(); }); } else { this.oSetting.id = UUID.UUID(); this.userService.SaveUser(this.oSetting).subscribe(m => { swal('Success', 'User added successfully...', 'success'); this.Settings = m; this.onNew(); }); } } } } <file_sep>import {Injectable} from '@angular/core' import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/share'; import 'rxjs/add/operator/startWith'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import { StorageService } from './local.storage'; @Injectable() export class AppGlobals { constructor(private local:StorageService){} // use this property for property binding TokenName="Access-Token"; Token:string; IsLogin:boolean; public isUserLoggedIn:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public setLoginStatus(isLoggedIn){ this.isUserLoggedIn.next(isLoggedIn); } SetToken(token:string) { this.local.add(this.TokenName,token); } GetToken() { return this.local.get(this.TokenName); } DeleteToken() { this.local.remove(this.TokenName); } SetUser(user:any) { this.local.add("CurrentUser",user); } GetUser() { return this.local.get("CurrentUser"); } DeleteUser() { this.local.remove("CurrentUser"); } }<file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/map"; @Injectable() export class SettingService { constructor(private http: Http) {} GetSetting(){ return this.http.get("/api/setting").map(res=>res.json()); } SaveSetting(data){ return this.http.post("/api/setting",data).map(res=>res.json()); } UpdateSetting(data){ return this.http.put("/api/setting/"+data.id,data).map(res=>res.json()); } DeleteSetting(data){ return this.http.delete("/api/setting/"+data.id,data).map(res=>res.json()); } } <file_sep>var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var cronjob = require('node-cron-job'); var CountryExcel = require('./SERVICE/country.js'); var fs = require('fs'); var multer = require('multer'); var config = require('config'); var moment = require('moment'); //var index= require('./routes/index'); //var tasks =require('./routes/tasks'); var app = express(); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'DataDB') }, filename: function (req, file, cb) { console.log(file) cb(null, file.originalname) } }) var upload = multer({ storage: storage }).any(); // View Engine app.set('views', path.join(__dirname, 'client/dist')); app.set('view engine', 'ejs'); app.engine('html', require('ejs').renderFile); //Set Static Folders Angulat Stuff app.use(express.static(path.join(__dirname, 'client/dist'))); // Body Parser; Middle Layer app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.all('/*', function (req, res, next) { // CORS headers res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.setHeader('Access-Control-Allow-Credentials', true); // Set custom headers for CORS res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Content-type,Accept,X-Access-Token,X-Key'); if (req.method == 'OPTIONS') { res.status(200).end(); } else { next(); } }); // Auth Middleware - This will check if the token is valid // Only the requests that start with /api/* will be checked for the token. // Any URL's that do not follow the below pattern should be avoided unless you // are sure that authentication is not needed app.use('/api/', require('./routes')); app.post('/fileupload', function (req, res) { upload(req, res, function (err) { if (err) { console.log("Error" + err); } else { console.log("File Name Upload"); CountryExcel.ProcessCountryExcel(); } res.send("Done"); }) }); // If no route is matched by now, it must be a 404 app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; res.redirect('/'); }); //app.use('/',index); //app.use('/api',tasks); var AppSetting = config.get("Application"); var port = AppSetting.portNumber; //app.listen(process.env.PORT, function () { app.listen(port, function () { console.log( ); console.log('Application is runnning on port ' + port); cronjob.setJobsPath(__dirname + '/jobs/xml.job.js'); // Absolute path to the jobs module. cronjob.startJob('CheckNewFiles'); cronjob.startJob('PurgeArchiveData'); });<file_sep>export class Contact { FirstName:string; LastName:string; Phone:string; AddressLine1:string; AddressLine2:string; City:string; State:string; Country:string; }<file_sep>export class Task { _id:string; Name:string; TaskDesc:string; TaskStatus:string; }<file_sep>import { Component ,Output,EventEmitter ,AfterViewInit} from '@angular/core'; import { AppGlobals} from '../../Services/app.global'; import { Router, ActivatedRoute} from '@angular/router'; import { correctHeight, BindAll,Login } from '../shared/app.helper'; @Component({ selector: 'app-master', templateUrl: './master.component.html', providers:[AppGlobals] }) export class MasterComponent implements AfterViewInit { title = 'Node Angular 2 Demo'; URLS:any[]; CurrentUser:any; @Output() LogOut= new EventEmitter<boolean>(); constructor(private appG: AppGlobals,private _route: ActivatedRoute, private _router: Router) { this.CurrentUser= this.appG.GetUser(); if(this.CurrentUser) { if(this.CurrentUser.role=="superadmin") { this.URLS= [ {url:'/user',cssClass:'fa fa-users',text:'User Setup'}, {url:'/settings',cssClass:'fa fa-wrench',text:'System Setting'}, ]; } else if(this.CurrentUser.role=="admin") { this.URLS= [ {url:'/dashboard',cssClass:'fa fa-th-large',text:'Dashboard'}, {url:'/user',cssClass:'fa fa-users',text:'User Setup'}, {url:'/setting',cssClass:'fa fa-wrench',text:'System Setting'}, {url:'/freightscode',cssClass:'fa fa-gear',text:'FreightCd Reference'}, {url:'/dailytran',cssClass:'fa fa-file-text-o',text:'Daily Log'}, {url:'/xmllog',cssClass:'fa fa-file-code-o',text:'XML History-Send Log'}, {url:'/country',cssClass:'fa fa-file-code-o',text:'Country Code'} ]; } else if (this.CurrentUser.role=="view") { this.URLS= [ {url:'/dashboard',cssClass:'fa fa-th-large',text:'Dashboard'}, {url:'/freightscode',cssClass:'fa fa-gear',text:'FreightCd Reference'}, {url:'/dailytran',cssClass:'fa fa-file-text-o',text:'Daily Log'}, {url:'/xmllog',cssClass:'fa fa-file-code-o',text:'XML History-Send Log'}, {url:'/country',cssClass:'fa fa-file-code-o',text:'Country Code'} ]; } else { this.URLS= [ {url:'/dashboard',cssClass:'fa fa-th-large',text:'Dashboard'}, {url:'/xmllog',cssClass:'fa fa-file-code-o',text:'XML History-Send Log'}, ]; } } } SignOut() { console.log("Sign Out User"); this.LogOut.emit(false); this.appG.DeleteToken(); this.appG.DeleteUser(); } ngAfterViewInit() { setTimeout(() => { correctHeight(); BindAll(); this._router.navigate(['/dashboard']); }, 3000) } } <file_sep>import { Component, EventEmitter, Output} from '@angular/core'; import { FreightService} from '../../Services/freight.service'; import { Router, ActivatedRoute} from '@angular/router'; import { Sorter} from '../../Services/app.sort'; import { UUID} from 'angular2-uuid'; import swal from 'sweetalert2'; import { Valid, ValidateMe, ValidateMeRule} from '../shared/app.helper'; @Component({ selector: 'app-freight', templateUrl: './freight.component.html', providers: [FreightService,Sorter] }) export class FreightComponent { oSetting: any; Settings: any[]; prev:number=-1; cols:any[]=[ { name:"fcode", title:"FreightCd", sorted:false, sortAs:"", sortable:true }, { name:"floc", title:"Dispatchment Loc", sorted:false, sortAs:"", sortable:true }, { name:"ttype", title:"TType", sorted:false, sortAs:"", sortable:true }, { name:"scode", title:"Status Code", sorted:false, sortAs:"", sortable:true }, { name:"sdesc", title:"Description", sorted:false, sortAs:"" , sortable:true } , { name:"shiptype", title:"Ship Type", sorted:false, sortAs:"" , sortable:true }, { name:"tdirection", title:"TDirection", sorted:false, sortAs:"" , sortable:true }, { name:"", title:"Action", sorted:false, sortAs:"" , sortable:false } ]; selectedRow:number; firstNameFilter:string; HideCross:boolean=true; constructor(private _route: ActivatedRoute, private _router: Router, private userService: FreightService,private sortService:Sorter) { userService.GetUser().subscribe(m => { this.Settings = m; }); } showCross() { if(this.firstNameFilter.length>0) this. HideCross=false; else this.HideCross=true; } onRemove() { this. HideCross=true; this.firstNameFilter=""; } onEdit(obj,i) { this.selectedRow=i; this.oSetting = Object.assign({}, obj); // obj; } SortColumn(key) { this.sortService.sort(key,this.Settings); } onDel(obj) { this.userService.DeleteUser(obj).subscribe(m => { swal('Success', 'Freight statuscode deleted successfully...', 'success'); this.Settings = m; this.onNew(); }); } onNew() { this.selectedRow=-1; this.oSetting = { "id": "", "fcode": "", "fdesc": "", "ttype": "", "scode": "", "sdesc": "", "shipType": "-", "tdirection": "" } ValidateMe("#FreightForm"); } Save() { if (Valid("#FreightForm")) { if (this.oSetting.id != "") { this.userService.UpdateUser(this.oSetting).subscribe(m => { swal('Success', 'Freight statuscode updated successfully...', 'success'); this.Settings = m; this.onNew(); }); } else { this.oSetting.id = UUID.UUID(); this.userService.SaveUser(this.oSetting).subscribe(m => { swal('Success', 'Freight statuscode added successfully...', 'success'); this.Settings = m; this.onNew(); }); } } } } <file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/map"; @Injectable() export class UserService { constructor(private http: Http) {} GetUser(){ return this.http.get("/api/user").map(res=>res.json()); } SaveUser(data){ return this.http.post("/api/user",data).map(res=>res.json()); } UpdateUser(data){ return this.http.put("/api/user/"+data.id,data).map(res=>res.json()); } DeleteUser(data){ return this.http.delete("/api/user/"+data.id,data).map(res=>res.json()); } Login(data){ return this.http.post("/api/login",data).map(res=>res.json()); } } <file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/map"; @Injectable() export class CountryService { constructor(private http: Http) {} GetCountry(){ return this.http.get("/api/country").map(res=>res.json()); } SaveCountry(data){ return this.http.post("/api/country",data).map(res=>res.json()); } UpdateCountry(data){ return this.http.put("/api/country/"+data.id,data).map(res=>res.json()); } DeleteCountry(data){ return this.http.delete("/api/country/"+data.id,data).map(res=>res.json()); } }
5991604fd7e7b4b3b3eeddaf204e8e9ed6f7d892
[ "JavaScript", "TypeScript" ]
34
TypeScript
amrikrudra/EDI-XML
088d20a53561693c0e9073cadd82952ab2098312
25fa290012296469d6756d1c779b69878145b449
refs/heads/master
<file_sep>export default{ apiKey: "<KEY>", authDomain: "vueapp-fd687.firebaseapp.com", databaseURL: "https://vueapp-fd687.firebaseio.com", projectId: "vueapp-fd687", storageBucket: "vueapp-fd687.appspot.com", messagingSenderId: "412256577593" }
a70dc50732481dced293d670288c2926a8391208
[ "JavaScript" ]
1
JavaScript
Przemyslawpomorski98/vueapp
9a0ef790dd5de3d787f0f1b3e5346ffa23105bc9
662fa3157aa2a02f6edd0bb1c8b34338416c308b
refs/heads/master
<file_sep>package anshima.com.webservice; public class Calculator implements CalculatorWS { @Override public int sum(int add1, int add2) { // TODO Auto-generated method stub return (add1 + add2); } @Override public int multiply(int mul1, int mul2) { // TODO Auto-generated method stub return (mul1 * mul2); } @Override public float divide(int div1, int div2) { // TODO Auto-generated method stub return (div1 / div2); } @Override public int subtract(int sub1, int sub2) { // TODO Auto-generated method stub return (sub1 - sub2); } }
c34c3b5d73811ecd709919a0d94c43cd1f6999a6
[ "Java" ]
1
Java
anshimagupta/soc
53d973751af8610c414f0e7f466dcd536036b385
e7a9482df01775a041f547c3193ff58f209ce9e3
refs/heads/master
<file_sep># forms-ng Note: This package is under development. Expect breaking changes in upcoming releases. ## Purpose * reuse form behavior in Angular * allow flexibility of design * type safety ## Installation ``` npm i forms-ng ``` ## Validation Errors The FormValidationErrorsComponent class holds the logic that shows and hides the validation errors. The validation errors are shown when the form control is touched. Validation errors are also shown for all form controls when the user attempts to submit the form with invalid data. Create a class that extends FormValidationErrorsComponent to adopt this functionality. validation-errors.component.ts ```typescript import { FormValidationErrorsComponent } from 'forms-ng'; @Component({ selector: 'app-validation-errors', templateUrl: './validation-errors.component.html', styleUrls: ['./validation-errors.component.css'] }) export class ValidationErrorsComponent extends FormValidationErrorsComponent { @Input() labelText = 'Field'; } ``` Create a template to show the errors. The errors property is provided by the FormValidationErrorsComponent class. validation-errors.component.html ```html <ng-container *ngIf="errors"> <div *ngIf="errors.email"><span>* {{labelText}} must be a valid email address.</span></div> <div *ngIf="errors.maxlength"><span>* The length of {{labelText}} must not exceed {{errors.maxlength.requiredLength}} characters.</span></div> <div *ngIf="errors.required"><span>* {{labelText}} is required.</span></div> </ng-container> ``` ## Form Controls To create a form control component, extend the FormControlComponent class and provide Angular's NG_VALUE_ACCESSOR. Implement the writeValue function so the component can hydrate itself when the value is updated by the FormGroup. The FormControlComponent class is an implementation of Angular's ControlValueAccessor. text-box.component.ts ```typescript import { FormControlComponent } from 'forms-ng'; @Component({ providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextBoxComponent), multi: true, }], selector: 'app-text-box', templateUrl: './text-box.component.html', styleUrls: ['./text-box.component.css'] }) export class TextBoxComponent extends FormControlComponent { @Input() isRequired: string; @Input() labelText: string; value: string; writeValue(value: any): void { this.value = value; } } ``` Create a template for the form control. * The touch and changeValue functions and the disabled and control properties are provided by the FormControlComponent class. * Send the control value to the FormValidationErrorsComponent to enable validation error display behavior. text-box.component.html ```html <div> <label>{{labelText}}</label> <span *ngIf="isRequired">*</span> </div> <div><input [disabled]="disabled" type="text" (blur)="touch()" [(ngModel)]="value" (ngModelChange)="changeValue($event)" /></div> <app-validation-errors [control]="control" [labelText]="labelText"></app-validation-errors> ``` ## Forms Start with a model that represents the form data. contact.model.ts ```typescript export class Contact { companyName: string; contactName: string; email: string; } ``` Create a component that implements FormComponent<T>. * Export the createFormGroup function so it can be used in nested forms (optional). contact-form.component.ts ```typescript import { FormComponent } from 'forms-ng'; export function contactFormGroup(formBuilder: FormBuilder, data: Contact) { return formBuilder.group({ companyName: [data.companyName, Validators.required], contactName: [data.contactName, Validators.required], email: [data.email, [Validators.required, Validators.email]] }); } @Component({ selector: 'contact-form', templateUrl: './contact-form.component.html' }) export class ContactFormComponent extends FormComponent<Contact> { createFormGroup = contactFormGroup; } ``` Create a template for the form using form controls. * The formGroup property and onSubmit function are provided by the FormComponent class * Use ngIf="formGroup" for situations when rendering happens before the variable is set * Include ng-content inside the form so the page can define its own submit button contact-form.component.html ```html <form *ngIf="formGroup" [formGroup]="formGroup" (submit)="onSubmit()"> <app-text-box isRequired formControlName="companyName" labelText="Company Name"></text-box> <app-text-box isRequired formControlName="contactName" labelText="Contact Name"></text-box> <app-text-box isRequired formControlName="Email" labelText="Email"></text-box> <ng-content></ng-content> </form> ``` ## Using It Wire up the form to your own submit function. * The submitForm event is provided by the FormComponent class * The event is fired when the form is submitted and passes validation. Add a button so the user can submit the form. example-contact.component.html ```html <h3>Example Contact</h3> <contact-form (submitForm)="submit($event)"> <button>Save</button> </contact-form> ``` example-contact.component.ts ```typescript @Component({ templateUrl: './example-contact-page.component.html' }) export class ExampleContactPageComponent { submit(contact: Contact) { alert('TODO: SEND TO SERVER: ' + JSON.stringify(contact)); } } ``` ## Set an Initial Value to a Form Send a value attribute to the FormComponent. ```html <app-address-form [value]="initialAddress" (submitForm)="submit($event)"> <button>Submit</button> </app-address-form> ``` ## Nested Forms Example See the project for full source code of example. ### Define a Model * This example shows the Address model as a child of the Contact model. contact.model.ts ```typescript import { Address } from './address.model'; export class Contact { name: string; email: string; address: Address; } ``` ### Create Child Form * Export the form group function so it can be used by another form component. address-form.component.ts ```typescript export function addressFormGroup(formBuilder: FormBuilder, data: Address) { return formBuilder.group({ address1: [data.address1, [Validators.required, Validators.maxLength(255)]], address2: [data.address2, Validators.maxLength(255)], city: [data.city, [Validators.required, Validators.maxLength(255)]], state: [data.state, [Validators.required, Validators.maxLength(255)]], zipCode: [data.zipCode, [Validators.required, validators.zipCode]] }); } @Component({ selector: 'app-address-form', templateUrl: './address-form.component.html', styleUrls: ['./address-form.component.css'] }) export class AddressFormComponent extends FormComponent<Address> { createFormGroup = addressFormGroup; } ``` ### Create Parent Form * Import the form group function from the child form. * Use it to create the parent form group. * Create a new data object for child by default because it does not play nice without an instance of an object. * Include the child form component in the parent form template. * Use [formGroup]="formGroup.get(fieldname)" to link the child form to the parent. contact-form.component.ts ```typescript import { addressFormGroup } from '../address-form/address-form.component'; export function contactFormGroup(formBuilder: FormBuilder, data: Contact) { return formBuilder.group({ email: [data.email, [Validators.required, Validators.email]], name: [data.name, Validators.required], address: addressFormGroup(formBuilder, data.address || new Address()) }); } @Component({ selector: 'app-contact-form', templateUrl: './contact-form.component.html', styleUrls: ['./contact-form.component.css'] }) export class ContactFormComponent extends FormComponent<Contact> { createFormGroup = contactFormGroup; } ``` contact-form.component.html ```html <form [formGroup]="formGroup" (submit)="onSubmit()"> <app-text-box [isRequired]="true" labelText="Name" formControlName="name"></app-text-box> <app-text-box [isRequired]="true" labelText="Email" formControlName="email"></app-text-box> <app-address-form [formGroup]="formGroup.get('address')"></app-address-form> <ng-content></ng-content> </form> ```<file_sep>export { FormControlComponent } from './lib/form-control.component'; export { FormComponent } from './lib/form.component'; export { FormList } from './lib/form-list'; export { FormsNgModule } from './lib/forms-ng.module'; export { FormService } from './lib/form.service'; export { FormValidationErrorsComponent } from './lib/form-validation-errors.component'; <file_sep>import { Injectable } from '@angular/core'; import { Address } from './address.model'; @Injectable() export class AppStateService { address: Address; } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormComponent } from 'forms-ng'; import { Contact } from '../../../contact.model'; import { FormBuilder, Validators } from '@angular/forms'; import { addressFormGroup } from '../address-form/address-form.component'; import { Address } from '../../../address.model'; export function contactFormGroup(formBuilder: FormBuilder, data: Contact) { return formBuilder.group({ email: [data.email, [Validators.required, Validators.email]], name: [data.name, Validators.required], address: addressFormGroup(formBuilder, data.address || new Address()) }); } @Component({ selector: 'app-contact-form', templateUrl: './contact-form.component.html', styleUrls: ['./contact-form.component.css'] }) export class ContactFormComponent extends FormComponent<Contact> { createFormGroup = contactFormGroup; } <file_sep>import { FormService } from './form.service'; import { FormStateService } from './form-state.service'; import { NgModule, ModuleWithProviders } from '@angular/core'; @NgModule() export class FormsNgModule { public static forRoot(): ModuleWithProviders<FormsNgModule> { return { ngModule: FormsNgModule, providers: [ FormStateService, FormService ] }; } } <file_sep>import { AppStateService } from '../../app-state.service'; import { Component, NgZone, ViewChild } from '@angular/core'; import { FormService } from 'forms-ng'; import { Contact } from 'src/app/contact.model'; import { ContactFormComponent } from '../../components/forms/contact-form/contact-form.component'; import { Router } from '@angular/router'; @Component({ selector: 'app-contact-page', templateUrl: './contact-page.component.html' }) export class ContactPageComponent { contact: Contact; displayText = ''; @ViewChild(ContactFormComponent) contactFormComponent: ContactFormComponent; constructor( private appStateService: AppStateService, private formService: FormService, private router: Router ) { } editAddress() { this.appStateService.address = this.contact.address; this.router.navigateByUrl('/address'); } reset() { this.contactFormComponent.formGroup.reset(); } submit(contact: Contact) { this.contact = contact; this.displayText = JSON.stringify(contact, null, 2); this.formService.disableAllControls(false); } } <file_sep>import { FormStateService } from './form-state.service'; import { ControlContainer, ControlValueAccessor, FormBuilder, AbstractControl } from '@angular/forms'; import { EventEmitter, Host, Input, Optional, Output, SkipSelf, Directive } from '@angular/core'; @Directive() export abstract class FormControlComponent implements ControlValueAccessor { // tslint:disable-next-line:variable-name private _disabled: boolean; @Input() formControlName: string; @Input() set disabled(disabled: boolean) { this._disabled = disabled; } get disabled() { return (this._disabled || this.formState.disableAllControls); } @Output() touched = new EventEmitter<void>(); public get control(): AbstractControl { return this.controlContainer.control.get(this.formControlName); } public changeValue: (value: any) => void; protected touchControl: () => void; constructor( @Optional() @Host() @SkipSelf() private controlContainer: ControlContainer, protected formBuilder: FormBuilder, private formState: FormStateService ) { } registerOnChange(fn: (value: any) => void) { this.changeValue = fn; } registerOnTouched(fn: () => void) { this.touchControl = fn; } touch() { this.touched.emit(); this.touchControl(); } public abstract writeValue(value: any): void; } <file_sep>import { FormValidationErrorsComponent } from 'forms-ng'; import { Component, Input } from '@angular/core'; @Component({ selector: 'app-validation-errors', templateUrl: './validation-errors.component.html', styleUrls: ['./validation-errors.component.css'] }) export class AppValidationErrorsComponent extends FormValidationErrorsComponent { @Input() labelText = 'Field'; } <file_sep>import { FormControlComponent } from 'forms-ng'; import { Component, forwardRef, Input } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { Code, Codes, CODES_ACCESSOR } from 'codes-ng'; @Component({ providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropDownComponent), multi: true, }, { provide: CODES_ACCESSOR, useExisting: forwardRef(() => DropDownComponent) }], selector: 'app-drop-down', templateUrl: './drop-down.component.html', styleUrls: ['./drop-down.component.css'] }) export class DropDownComponent extends FormControlComponent implements Codes { // tslint:disable-next-line:variable-name private _codes: Code[]; @Input() get codes() { return this._codes; } set codes(codes: Code[]) { this._codes = codes; } @Input() isRequired: string; @Input() labelText: string; value: string; writeValue(value: any): void { this.value = value; } } <file_sep>import { FormStateService } from './form-state.service'; import { Injectable } from '@angular/core'; @Injectable() export class FormService { constructor( private formState: FormStateService ) { } public disableAllControls(disableAllControls = true) { this.formState.disableAllControls = disableAllControls; } } <file_sep>import { AppStateService } from './app-state.service'; import { StateCodesDirective } from './components/forms/address-form/state-codes.directive'; import { FormsModule as FormsModule_ng} from '@angular/forms'; import { FormsNgModule } from 'forms-ng'; import { ContactFormComponent } from './components/forms/contact-form/contact-form.component'; import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; import { TextBoxComponent } from './components/form-controls/text-box/text-box.component'; import { AppValidationErrorsComponent } from './components/validation-errors/validation-errors.component'; import { AddressFormComponent } from './components/forms/address-form/address-form.component'; import { DropDownComponent } from './components/form-controls/drop-down/drop-down.component'; import { ContactPageComponent } from './pages/contact-page/contact-page.component'; import { AddressPageComponent } from './pages/address-page/address-page.component'; @NgModule({ declarations: [ AppComponent, ContactFormComponent, TextBoxComponent, AppValidationErrorsComponent, AddressFormComponent, DropDownComponent, StateCodesDirective, ContactPageComponent, AddressPageComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule_ng, ReactiveFormsModule, FormsNgModule.forRoot() ], providers: [AppStateService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { FormStateService } from './form-state.service'; import { AbstractControl, ValidationErrors } from '@angular/forms'; import { Directive, Input } from '@angular/core'; @Directive() export abstract class FormValidationErrorsComponent { @Input() control: AbstractControl; public get errors(): ValidationErrors { if (this.control && this.control.errors && (this.control.touched || this.formState.showAllValidationErrors)) { return this.control.errors; } return null; } constructor( private formState: FormStateService ) { } } <file_sep>import { FormControl } from '@angular/forms'; export function zipCode(control: FormControl) { if (!control.value || /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(control.value)) { return null; } return { zipcode: { valid: false } }; } <file_sep>import { FormArray } from '@angular/forms'; export class FormList<T> { public list: T[]; public static create<TValue>(list?: TValue[]): FormList<TValue> { if (!list) { return undefined; } return { list }; } public static formArray<TValue>(formArray: FormArray): { list: FormArray } { return { list: formArray }; } public static formGroup<TValue>(formList: FormList<TValue>): { list: [TValue[]] } { return { list: [FormList.getValue(formList)] }; } public static getValue<TValue>(formList: FormList<TValue>): TValue[] { return formList && formList.list; } } <file_sep>import { FormStateService } from './form-state.service'; import { EventEmitter, Directive, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, AbstractControl } from '@angular/forms'; import { SessionObject } from 'session-object'; import { Subscription } from 'rxjs'; @Directive() export abstract class FormComponent<TModel> implements OnInit, OnDestroy { private initialValue: TModel; private sessionData: SessionObject<TModel>; private submitted: boolean; private subscriptions: Subscription[]; public abstract createFormGroup: (formBuilder: FormBuilder, data: TModel) => FormGroup; public get hasPendingChanges(): boolean { return !this.submitted && this.formGroup.dirty; } @Input() set value(value: TModel) { if (this.formGroup) { this.formGroup.reset(value); } else { this.initialValue = value; } } get value() { return (this.formGroup) ? this.formGroup.value : this.initialValue; } private _formGroup: FormGroup; @Input() set formGroup(formGroup: FormGroup) { this._formGroup = formGroup; this.onSetFormGroup(formGroup); } get formGroup() { return this._formGroup; } @Input() sessionKey: string; @Output() submitForm = new EventEmitter<TModel>(); public get control(): AbstractControl { return this.formGroup; } private clearSessionData() { if (this.sessionData) { this.sessionData.delete(); } } private updateSessionData(value: any) { if (this.sessionData) { this.sessionData.set(value); } } constructor( protected formBuilder: FormBuilder, private formState: FormStateService ) { } ngOnInit() { if (this.sessionKey) { this.sessionData = new SessionObject<any>(`forms::form-component::session-data::${this.sessionKey}`); } const sessionDataValue = this.sessionData && this.sessionData.get(); const initialFormGroupValue = sessionDataValue || this.initialValue || {} as TModel; if (!this.formGroup) { this.formGroup = this.createFormGroup(this.formBuilder, initialFormGroupValue); } if (sessionDataValue) { this.formGroup.markAsDirty(); } else { this.updateSessionData(initialFormGroupValue); } this.subscriptions = [ this.formGroup.valueChanges.subscribe(value => this.updateSessionData(value)) ]; } ngOnDestroy() { this.subscriptions.forEach(subscription => subscription.unsubscribe()); this.clearSessionData(); } onSubmit() { if (!this.formGroup.valid) { this.formState.showAllValidationErrors = true; return; } this.submitted = true; this.submitForm.emit(this.formGroup.value); } protected onSetFormGroup(formGroup: FormGroup) { } public createNewFormGroup(data: TModel): FormGroup { return this.createFormGroup(this.formBuilder, data); } } <file_sep>import { FormComponent } from 'forms-ng'; import { Component } from '@angular/core'; import { Address } from '../../../address.model'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import * as validators from '../validators'; export function addressFormGroup(formBuilder: FormBuilder, data: Address) { return formBuilder.group({ address1: [data.address1, [Validators.required, Validators.maxLength(255)]], address2: [data.address2, Validators.maxLength(255)], city: [data.city, [Validators.required, Validators.maxLength(255)]], state: [data.state, [Validators.required, Validators.maxLength(255)]], zipCode: [data.zipCode, [Validators.required, validators.zipCode]] }); } @Component({ selector: 'app-address-form', templateUrl: './address-form.component.html', styleUrls: ['./address-form.component.css'] }) export class AddressFormComponent extends FormComponent<Address> { createFormGroup = addressFormGroup; onSetFormGroup(formGroup: FormGroup) { console.log("Form Group has been set.", formGroup); } } <file_sep>import { AppStateService } from '../../app-state.service'; import { Component } from '@angular/core'; import { FormService } from 'forms-ng'; import { Contact } from 'src/app/contact.model'; import { Address } from 'src/app/address.model'; @Component({ selector: 'app-address-page', templateUrl: './address-page.component.html' }) export class AddressPageComponent { displayText = ''; get address() { return this.appStateService.address; } constructor( private appStateService: AppStateService, private formService: FormService ) { } reset() { this.appStateService.address = new Address(); } submit(contact: Contact) { this.displayText = 'processing...'; this.formService.disableAllControls(); setTimeout(() => { this.displayText = JSON.stringify(contact, null, 2); this.formService.disableAllControls(false); }, 1000); } }
7eb41db01ac1593a640dba2286221d5c07b81203
[ "Markdown", "TypeScript" ]
17
Markdown
better-automation/forms-ng
d2668ec0c56a805cfaa8b64fa0fd7800632f4e0d
0d18aae8e989550ce196fcfb14cf07f78a3ae9cf
refs/heads/master
<repo_name>ccschmitz/oh-my-zsh<file_sep>/custom/aliases.zsh # Git alias g="git" alias gs="git status" alias gc="git commit" alias gcv="git commit -v" alias gA"git add -A" alias gg="git-goggles" # Reset Coreaudio service alias resetaudio="sudo kill -9 `ps ax|grep 'coreaudio[a-z]' | awk '{print $1}'`" # Redis alias startredis="redis-server /usr/local/etc/redis.conf" # PostgreSQL alias pgstop="pg_ctl -D /usr/local/var/postgres stop -s -m fast" alias pgstart="pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start"
5342d37d5624181fedb041c5d69e22c4c481f8d1
[ "Shell" ]
1
Shell
ccschmitz/oh-my-zsh
95b9eac20fbfef83fad200dafcda5f18aa0c4e2a
65888601aa54c1a1ce0e0be36a8822fc9c2ca504
refs/heads/master
<repo_name>twfth9/LRDT-ThomasFork<file_sep>/Documents/Igniter code/Ground Station/GSModules/Logging.py import os from datetime import datetime import time class Logger(object): def __init__(self): self.startTime = time.time() self.isOpen = False def start(self, filepath): self.startDate = datetime.now() self.fname = "IgniterUILog-" + self.startDate.strftime("%Y%m%d-%H%M%S") + ".txt" self.filepath = os.path.join(filepath, self.fname) if not os.path.exists(filepath): os.makedirs(filepath) global fil fil = open(self.filepath, 'w+') self.isOpen = True fil.writelines([ "FileType=text/igniter/pressure\r", "FileVersion=0.1\r", "StartTime=" + self.startDate.strftime("%Y-%m-%dT%H:%M:%S") + "\r", "Title=IgniterPressureLog" + self.startDate.strftime("%Y%m%d-%H%M%S") + "\r", "Author=Missouri S&T Rocket Design Team" + "\r", ]) def log(self, strn): fil.write(str(round((time.time() - self.startTime), 3)) + ": " + strn) def halt(self): self.isOpen = False fil.close() def is_open(self): return self.isOpen <file_sep>/Documents/Igniter code/Ground Station/GSModules/ArduinoConfigureWindow.py import PySimpleGUI as sg configureWindow = sg.Window('Arduino Configuration', grab_anywhere=False, resizable=True) diagram = sg.Image('ArduinoUnoImg1.png', key='DIAGRAM') left_col = [[sg.Button("Pin A" + str(0), button_color=('White', 'Red'), key="ConfigPinA" + str(0))], [sg.Button("Pin A" + str(1), button_color=('White', 'Red'), key="ConfigPinA" + str(1))], [sg.Button("Pin A" + str(2), button_color=('White', 'Red'), key="ConfigPinA" + str(2))], [sg.Button("Pin A" + str(3), button_color=('White', 'Red'), key="ConfigPinA" + str(3))], [sg.Button("Pin A" + str(4), button_color=('White', 'Red'), key="ConfigPinA" + str(4))], [sg.Button("Pin A" + str(5), button_color=('White', 'Red'), key="ConfigPinA" + str(5))],] right_col_buttons = [[sg.Button("Pin " + str(13), button_color=('White', 'Red'), key="ConfigPin" + str(13))], [sg.Button("Pin " + str(12), button_color=('White', 'Red'), key="ConfigPin" + str(12))], [sg.Button("Pin " + str(11), button_color=('White', 'Red'), key="ConfigPin" + str(11))], [sg.Button("Pin " + str(10), button_color=('White', 'Red'), key="ConfigPin" + str(10))], [sg.Button("Pin " + str(9), button_color=('White', 'Red'), key="ConfigPin" + str(9))], [sg.Button("Pin " + str(8), button_color=('White', 'Red'), key="ConfigPin" + str(8))], [sg.Button("Pin " + str(7), button_color=('White', 'Red'), key="ConfigPin" + str(7))], [sg.Button("Pin " + str(6), button_color=('White', 'Red'), key="ConfigPin" + str(6))], [sg.Button("Pin " + str(5), button_color=('White', 'Red'), key="ConfigPin" + str(5))], [sg.Button("Pin " + str(4), button_color=('White', 'Red'), key="ConfigPin" + str(4))], [sg.Button("Pin " + str(3), button_color=('White', 'Red'), key="ConfigPin" + str(3))], [sg.Button("Pin " + str(2), button_color=('White', 'Red'), key="ConfigPin" + str(2))], [sg.Button("Pin " + str(1), button_color=('White', 'Red'), key="ConfigPin" + str(1))], [sg.Button("Pin " + str(0), button_color=('White', 'Red'), key="ConfigPin" + str(0))],] layout = [[sg.Text("This is a test")], [sg.Column(left_col), diagram, sg.Column(right_col_buttons)]] """ while True: event, values = configureWindow.read(timeout=10) if event is None: break if "ConfigPin" in event: name = "Main CH4" pin = 4 if event == "ConfigPin" + str(pin): configureWindow.element("ConfigPin" + str(pin)).Update(name) """ configureWindow.Close()<file_sep>/Documents/Igniter code/Ground Station/IgniterUI.py import PySimpleGUI as sg import threading import serial import math import serial.tools.list_ports from datetime import datetime from GSModules import ListComPorts from GSModules import UIElements from GSModules import SerialStuff as sb from GSModules.Logging import Logger from GSModules import ArduinoConfigureWindow as cfg # Valve states isValveOpen = [False, False, False, False, False, False] # Create the Window and Finalize it. Then fullscreen window = sg.Window('RocketView', UIElements.layout, grab_anywhere=False, resizable=True) # Declaring buffer string to store serial data buffer = "" dataString = "" ser = serial.Serial(None) #Create serial port object f = Logger() # Event Loop to process "events" and get the "values" of the inputs while True: event, values = window.read(timeout=10) # Button Reactions if event is None: break if "Configure" in event: configureWindow = sg.Window('Arduino Configuration', cfg.layout, grab_anywhere=True, resizable=True) if not ser.is_open: if event == 'COM_Connect': try: # OPENING SERIAL PORT ser = serial.Serial(values['COM_Combo'], 9600, timeout=1) ser.write(bytearray([0x05])) if __name__ == '__main__': window.FindElement('COM_Combo').update(values=ListComPorts.serial_ports()) window.FindElement('COM_Connect').update(values['COM_Combo'], button_color=('White', 'Green')) window.FindElement('COM_Enquire').update(button_color=('White', 'Red')) except serial.SerialException: #IF PORT CAN'T BE OPENED print("Unable to Open Port") else: if "COM" in event: if "Connect" in event: # CLOSING SERIAL PORT ser.close() window.FindElement('COM_Combo').update(values=ListComPorts.serial_ports()) window.FindElement('COM_Connect').update('Open', button_color=('White', 'Red')) window.FindElement('COM_Enquire').update(button_color=('White', 'Red')) window.Element('P1').Update("XXXXXXXXXX") window.Element('P2').Update("XXXXXXXXXX") window.Element('P3').Update("XXXXXXXXXX") window.Element('P4').Update("XXXXXXXXXX") window.Element("STAGE" + str(1)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(2)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(3)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(4)).Update(button_color=('White', 'Red')) for x in range(6): window.Element("valve" + str(x)).Update(button_color=('White', 'Red')) if f.is_open(): f.halt() window.Element('filein').update('Start Recording', button_color=('White', 'Red')) elif "Refresh" in event: if __name__ == '__main__': window.FindElement('COM_Combo').update(values=ListComPorts.serial_ports()) elif "Enquire" in event: try: ser.write(bytearray([0x05])) except serial.SerialException: print("Port Closed") elif "dropdown" in event: #filename = sg.popup_get_file('file to open', no_window=True) print("Got em") elif "filein" in event: if not f.is_open(): f.start(values['input']) window.Element('filein').update('Recording', button_color=('White', 'Green')) else: f.halt() window.Element('filein').update('Start Recording', button_color=('White', 'Red')) elif "VALVE" in event: for x in range(0,6): if str(x) in event: packet = [0x01, 0x56, 0x30, 0x31, 0x02, x+0x30, 0x04] ser.write(bytearray(packet)) elif "STAGE" in event: if str(0) in event: print("closing...") # Send command to close all valves packet = [0x01, 0x43, 0x30, 0x35, 0x02, 0x43, 0x4c, 0x4f, 0x53, 0x45, 0x04] ser.write(bytearray(packet)) if (f.is_open()): f.log("Closing..." + "\r") elif str(1) in event: print("arming...") # Send command to arm packet = [0x01, 0x43, 0x30, 0x33, 0x02, 0x41, 0x52, 0x4d, 0x04] ser.write(bytearray(packet)) if (f.is_open()): f.log("Arming..." + "\r") elif str(2) in event: print("firing...") packet = [0x01, 0x43, 0x30, 0x34, 0x02, 0x46, 0x49, 0x52, 0x45, 0x04] ser.write(bytearray(packet)) if (f.is_open()): f.log("Firing..." + "\r") elif str(3) in event: print("purging...") packet = [0x01, 0x43, 0x30, 0x35, 0x02, 0x50, 0x55, 0x52, 0x47, 0x45, 0x04] ser.write(bytearray(packet)) if (f.is_open()): f.log("Purging..." + "\r") # Updating GUI to reflect valve states for x in range(0,6): if isValveOpen[x] == True: window.FindElement("VALVE" + str(x)).Update(button_color=('White', 'Green')) else: window.FindElement("VALVE" + str(x)).Update(button_color=('White', 'Red')) #*****UPDATE PRESSURE READINGS***** # Parses serial buffer from microcontroller # Converts raw data into float value, used to update GUI if ser.is_open: while ser.in_waiting: inChar = ser.read().decode('ASCII') buffer = buffer + inChar if (inChar == chr(6)): buffer = "" window.FindElement('COM_Enquire').update(button_color=('White', 'Green')) if (inChar == chr(4)): if (buffer.find(chr(1)) >= 0): buffer = buffer[buffer.find(chr(1)):( buffer.find(chr(4)) + 1)] # Trim off excess characters before and after packet packet_type = buffer[1] upperNibble: int = ord(buffer[2]) lowerNibble: int = ord(buffer[3]) # UPPER NIBBLE if (upperNibble > 0x40): # if a letter upperNibble = upperNibble & 0b00001111 # strip off upper nibble(only indicates that value is a letter) upperNibble = upperNibble + 0b00001001 # upperNibble now equals 0x0A - 0x0F else: upperNibble = upperNibble & 0b00001111 # upperNibble now equals 0x00 - 0x09 upperNibble = upperNibble << 4 # upperNibble now represents upper byte of dataBytes # LOWER NIBBLE if (lowerNibble > 0x40): # if letter lowerNibble = lowerNibble & 0b00001111 # strip off upper nibble lowerNibble = lowerNibble + 0b00001001 # lowerNibble now equals 0x0A - 0x0F lowerNibble = lowerNibble & 0b00001111 # lowerNibble now equals 0x00 - 0x09 if it was a number packet_dataSize = upperNibble | lowerNibble # combining upper and lower bytes to make final char(UUUU LLLL) dataString = buffer[5:-1] # sets data string of packet to data pulled from _inputString buffer = "" # Clear buffer # *** UPDATE PRESSURE READINGS *** # *** CAN WE CHECK THESE CALCULATIONS??? # *** 5V ON PIN = 28 PSI??? if (packet_type == 'D'): pdata1 = dataString[dataString.find('A') + 1:dataString.find('B')] pdata1 = int(pdata1) * (5.0 / 1023.0) * (14000.0 / 2500.0) window.Element('P1').Update(round(pdata1, 2)) pdata2 = dataString[dataString.find('B') + 1:dataString.find('C')] pdata2 = int(pdata2) * (5.0 / 1023.0) * (14000.0 / 2500.0) window.Element('P2').Update(round(pdata2, 2)) pdata3 = dataString[dataString.find('C') + 1:dataString.find('D')] pdata3 = int(pdata3) * (5.0 / 1023.0) * (14000.0 / 2500.0) window.Element('P3').Update(round(pdata3, 2)) pdata4 = dataString[dataString.find('D') + 1:] pdata4 = int(pdata4) * (5.0 / 1023.0) * (14000.0 / 2500.0) window.Element('P4').Update(round(pdata4, 2)) if(f.is_open()): f.log("Pressure 1: " + str(round(pdata1, 2)) + "\r") f.log("Pressure 2: " + str(round(pdata2, 2)) + "\r") f.log("Pressure 3: " + str(round(pdata3, 2)) + "\r") f.log("Pressure 4: " + str(round(pdata4, 2)) + "\r") if (packet_type == 'M'): if (dataString == "IGNITER ARMED"): window.Element("STAGE" + str(1)).Update(button_color=('White', 'Green')) window.Element("STAGE" + str(2)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(3)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(0)).Update(button_color=('White', 'Red')) if (dataString == "IGNITER FIRING"): window.Element("STAGE" + str(1)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(2)).Update(button_color=('White', 'Green')) window.Element("STAGE" + str(3)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(0)).Update(button_color=('White', 'Red')) if (dataString == "IGNITER PURGING"): window.Element("STAGE" + str(1)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(2)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(3)).Update(button_color=('White', 'Green')) window.Element("STAGE" + str(0)).Update(button_color=('White', 'Red')) if (dataString == "IGNITER CLOSED"): window.Element("STAGE" + str(1)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(2)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(3)).Update(button_color=('White', 'Red')) window.Element("STAGE" + str(0)).Update(button_color=('White', 'Green')) print(dataString) if (f.is_open()): f.log(dataString + "\r") if (packet_type == 'V'): for x in range(6): isValveOpen[x] = bool(int(dataString[x])) print("Valve States: " + dataString) if (f.is_open()): f.log("Valve States: " + dataString + "\r") else: buffer = "" # If only 1 end of packet is found, data somehow corrupted, clear buffer window.close()
78d910cc1454d996a60f1208a0df4c0109f4c217
[ "Python" ]
3
Python
twfth9/LRDT-ThomasFork
2a309859f967277a36c76cd9d9b6911f19481b09
179c57fe1e071548dc035826f915d4f02272400e
refs/heads/master
<repo_name>asanc305/cop-lab4<file_sep>/test/test.c #include <stdio.h> #include <stdlib.h> #include <string.h> int main( int argc, char* argv[] ) { unsigned char buffer1 ; FILE* input_file ; FILE* output_file ; //open files input_file = fopen( "/test/war-and-peace.txt", "rb" ) ; output_file = fopen( "/test/output", "wb" ) ; //check files if(input_file == NULL || output_file == NULL) { if( input_file == NULL ) printf("Error opening input file\n") ; else printf("Error opening output file\n") ; return -1 ; } //read first byte fread( &buffer1, 1, 1, input_file ) ; while( !feof(input_file) ) { fwrite( &buffer1, 1, 1, output_file ) ; //fwrite( " !!MORE!! ", 1, 10, output_file ) ; fread( &buffer1, 1, 1, input_file ) ; } fclose( input_file ) ; fclose( output_file ) ; }
014e7f0c0f8697d8577cf7283c8e2a536f105511
[ "C" ]
1
C
asanc305/cop-lab4
e4a34daf6182707f6e15afe4ef9fc243641ad899
514b4412e0ff2442a41ef3425fe6a71741351ae8
refs/heads/master
<repo_name>iamalibabaei/docker-exim-smtp<file_sep>/README.md # Docker Exim Relay Image [Exim](http://exim.org/) relay [Docker](https://docker.com/) image based on [Alpine](https://alpinelinux.org/) Linux. A light weight Docker image for an Exim mail relay, based on the official Alpine image. For extra security, the container runs as exim not root. ## [Docker Run](https://docs.docker.com/engine/reference/run) ### Default setup This will allow relay from all private address ranges and will relay directly to the internet receiving mail servers Smtp Auth (`SMTP_PLAINAUTH_USERNAME` / `SMTP_PLAINAUTH_PASSWORD` ) is optional. ```shell docker run \ --name smtp \ --restart always \ -e SMTP_PLAINAUTH_USERNAME= \ -e SMTP_PLAINAUTH_PASSWORD= \ -h my.host.name \ -d \ -p 25:25 \ akit042/exim-smtp ``` ### Smarthost setup To send forward outgoing email to a smart relay host ```shell docker run \ --restart always \ -h my.host.name \ -d \ -p 25:25 \ -e SMARTHOST=some.relayhost.name \ -e SMTP_USERNAME=someuser \ -e SMTP_PASSWORD=<PASSWORD> \ akit042/exim-smtp ``` ## [Docker Compose](https://docs.docker.com/compose/compose-file) ```yml version: "2" services: smtp: image: akit042/exim-smtp restart: always ports: - "25:25" hostname: my.host.name environment: - SMARTHOST=some.relayhost.name - SMTP_USERNAME=someuser - SMTP_PASSWORD=<PASSWORD> ``` ## Other Variables ###### LOCAL_DOMAINS * List (colon separated) of domains that are delivered to the local machine * Defaults to the hostname of the local machine * Set blank to have no mail delivered locally ###### RELAY_FROM_HOSTS * A list (colon separated) of subnets to allow relay from * Set to "\*" to allow any host to relay - use this with RELAY_TO_DOMAINS to allow any client to relay to a list of domains * Defaults to private address ranges: 10.0.0.0/8:172.16.0.0/12:192.168.0.0/16 ###### RELAY_TO_DOMAINS * A list (colon separated) of domains to allow relay to * Defaults to "\*" to allow relaying to all domains * Setting both RELAY_FROM_HOSTS and RELAY_TO_DOMAINS to "\*" will make this an open relay * Setting both RELAY_FROM_HOSTS and RELAY_TO_DOMAINS to other values will limit which clients can send and who they can send to ###### RELAY_TO_USERS * A whitelist (colon separated) of recipient email addresses to allow relay to * This list is processed in addition to the domains in RELAY_TO_DOMAINS * Use this for more precise whitelisting of relayable mail * Defaults to "" which doesn't whitelist any addresses ###### SMARTHOST * A relay host to forward all non-local email through ###### SMTP_USERNAME * The username for authentication to the smarthost ###### SMTP_PASSWORD * The password for authentication to the smarthost - leave this blank to disable authenticaion ## Docker Secrets The smarthost password can also be supplied via docker swarm secrets / rancher secrets. Create a secret called SMTP_PASSWORD and don't use the SMTP_PASSWORD environment variable ## Persist Data You may want to persist your mail queue Just mount your desired path to /var/spool/exim ## Debugging The logs are sent to /dev/stdout and /dev/stderr and can be viewed via docker logs ```shell docker logs smtp ``` ```shell docker logs -f smtp ``` Exim commands can be run to check the status of the mail server as well Print a count of the messages in the queue: ```shell docker exec -it smtp exim -bpc ``` Print a listing of the messages in the queue (time queued, size, message-id, sender, recipient): ```shell docker exec -it smtp exim -bp ``` Remove all frozen messages: ```shell docker exec -it smtp exim -bpu | grep frozen | awk {'print $3'} | xargs docker exec -i smtp exim -Mrm ``` Test how exim will route a given address: ```shell docker exec -it smtp exim -bt <EMAIL> ``` ``` <EMAIL> router = dnslookup, transport = remote_smtp host gmail-smtp-in.l.google.com [fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b] MX=5 host gmail-smtp-in.l.google.com [64.233.167.27] MX=5 host alt1.gmail-smtp-in.l.google.com [fdf8:f53e:61e4::18] MX=10 host alt1.gmail-smtp-in.l.google.com [172.16.58.3] MX=10 host alt2.gmail-smtp-in.l.google.com [2404:6fc00:e968:6179::de52:7100] MX=20 host alt2.gmail-smtp-in.l.google.com [172.16.17.32] MX=20 host alt3.gmail-smtp-in.l.google.com [2404:6fc00:db20:35b:7399::5] MX=30 host alt3.gmail-smtp-in.l.google.com [172.16.58.3] MX=30 host alt4.gmail-smtp-in.l.google.com [26fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b] MX=40 host alt4.gmail-smtp-in.l.google.com [74.125.195.27] MX=40 ``` Display all of Exim's configuration settings: ```shell docker exec -it smtp exim -bP ``` View a message's headers: ```shell docker exec -it smtp exim -Mvh <message-id> ``` View a message's body: ```shell docker exec -it smtp exim -Mvb <message-id> ``` View a message's logs: ```shell docker exec -it smtp exim -Mar <message-id> ``` Remove a message from the queue: ```shell docker exec -it smtp exim -Mrm <message-id> [ <message-id> ... ] ``` <file_sep>/entrypoint.sh #!/bin/ash set -e chown -R exim: /var/spool/exim if [ "${1:0:1}" = '-' ]; then exec exim "$@" fi if [ $1 = "exim" ]; then $@ & trap "kill $!" SIGINT SIGTERM wait exit $? else set -- $@ fi
5b1c17ca04e25575226b56a8b5419db2c6edadb6
[ "Markdown", "Shell" ]
2
Markdown
iamalibabaei/docker-exim-smtp
e05b718fa20087ad097a67cdfee71df4dfb7b83c
89121d4547f24ae18cd236988a0e917169a59f58
refs/heads/master
<repo_name>hucongting/beifen<file_sep>/文件备份/TestPhoneSMS01/src/com/sve/util/SendSMS.java package com.sve.util; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 接收页面传过来的手机号码 * 测试根据手机号接收的验证码 * @作者 soft01 * 2018年6月26日下午4:30:12 */ @WebServlet("/sendSMS") public class SendSMS extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String phone = request.getParameter("phone"); //获取验证码 //String code = GetMessageCode.getCode(phone); //测试数据 String code = "123465"; session.setAttribute("sms_code", code); String str = (String) session.getAttribute("sms_code"); System.out.println(phone+"----> 验证码:"+str); } } <file_sep>/文件备份/ssm.shiro.sql create database test; use test; insert into user(username,userpwd) value('<PASSWORD>','<PASSWORD>'); insert into user(username,userpwd) value('<PASSWORD>','<PASSWORD>'); insert into user(username,userpwd) value('wangwu','<PASSWORD>'); insert into city_pm(city_name,city_pm) value('广州',254); insert into city_pm(city_name,city_pm) value('深圳',152); insert into city_pm(city_name,city_pm) value('珠海',232); create table user( userid int primary key auto_increment, username varchar(20) not null, userpwd varchar(200) not null ); select * from user; select * from user_roles; -- 角色表 create table user_roles( rolesid int primary key auto_increment, userid int not null, rolesname varchar(20) not null ); alter table user_roles add constraint FK_USER_ROLES_USERID foreign key(userid) references user(userid); insert into user_roles(userid,rolesname) values(4,'admin'); insert into user_roles(userid,rolesname) values(5,'user'); <file_sep>/文件备份/java_api/src/main/java/com/cbt/reflect/ConstrutorDemo.java package com.cbt.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Scanner; /** * Class.newInstance() 与 Constructor.newInstance() * - Class.newInstance()只能调用类中无参数构造器!如果没有无参数构造器则抛出异常 * - Constructor.newInstance()可以调用任何一个构造器 * 在实际工作中,大部分类都是无参数构造器!所以在利用发射创建对象时,Class.newInstance()更加方便常用。 * * @作者 soft01 * 2018年6月25日下午3:11:41 */ public class ConstrutorDemo { @SuppressWarnings("resource") public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Scanner scanner = new Scanner(System.in); System.out.println("输入类名:"); Class cls = Class.forName(scanner.nextLine()); //找到类中的无参构造 //在cls对应的类型上查找一个int类型参数的构造器,找到了赋值给constructor //如果没有找到构造器则抛出异常! Constructor constructor = cls.getConstructor(int.class); //一定传递类型相同的数据,否则将出现异常 Object obj = constructor.newInstance(58); Constructor constructors = cls.getConstructor(int.class,int.class); Object objs = constructors.newInstance(20,30); //检查创建对象 System.out.println(obj); System.out.println(objs); } } <file_sep>/文件备份/java_api/src/main/java/com/cbt/reflect/ParamDemo.java package com.cbt.reflect; /** * 方法的变长参数现象: * * @作者 soft01 * 2018年6月25日下午4:35:06 */ public class ParamDemo { public static void main(String[] args) { test(); test(1); test(3,5); test(6,8); } /** * 本质上变长参数就是数组参数! * 1.使用...声明的参数称为变长参数 * 2.在调用时可以传递任意多个参数 * 3.在方法中,按照数组对变长参数进行处理 * 4.变长参数可以直接接受数组参数 * 5.一个方法只能有一个变长参数,而且只能放在最后一个参数 * 6.技巧: 如果想接收多态参数可以使用Object... * * @param a */ public static void test(int... a) { //a实际上是一个int[] 数组 //test()时候是0长度数组a={} //test(1)使用1个长度数组a={1} //test(2,3)参数是两个长度数组a={2,3} int sum = 0; for(int aa : a) { sum += aa; } System.out.println(sum); } public static void test2(String str, String...strings) { } } <file_sep>/文件备份/java_api/src/main/java/com/cbt/reflect/Goo.java package com.cbt.reflect; public class Goo { int b; int c; public Goo() {} public Goo(int b) { this.b = b; } public Goo(int b,int c) { this.b = b; this.c = c; } public void test() { System.out.println("Goo test()..."); } private void who(String str, int age) { System.out.println(str+">>>>>"+age); } @Override public String toString() { return "Goo [b=" + b + ", c=" + c + "]"; } } <file_sep>/文件备份/java_api/webserver/readme.txt 本次改动: 独立完成功能:修改密码 1:提供相关页面:update_pwd.html,update_success.html, update_fail.html,no_user.html 2:修改密码页面中要求用户输入要修改的用户名,旧密码,以及 新密码,form表单提交路径:update,提交方式:post 3:提供修改密码的业务处理类:UpdateServlet 修改业务要求: 3.1:若没有此用户则跳转no_user.html,提示无此用户 3.2: 若旧密码与该用户原密码不一致,则跳转到修改失败页面 3.3:若找到此用户,并且旧密码输入正确,则修改该用户的密码 为新密码并跳转到修改成功页面 4:再配置文件conf/servlets中添加请求与该Servlet的对应关系 ClientHandler将来的大致工作流程: 1:解析请求 2:处理请求 3:响应客户端
afa08851cf87b41119a4c048cbe11f7d54f2e296
[ "Java", "Text", "SQL" ]
6
Java
hucongting/beifen
24b81d816afcd8ba6eecf62d200f4041fabe64e8
7d3289a2426c8d18fb6df543eb30b22a115ea7dc
refs/heads/master
<repo_name>rajansanthanam/support<file_sep>/Tools/Utilities/ports.sh #!/usr/bin/env bash ssh -i ~/.ssh/sanju.pem -f -N -L 18391:10.10.48.216:18391 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 7180:10.10.48.216:7180 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 18631:10.10.48.216:18631 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 18372:10.10.48.216:18372 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 18381:10.10.48.216:18381 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 18382:10.10.48.216:18382 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 18390:10.10.48.216:18390 172.16.58.3 ssh -i ~/.ssh/sanju.pem -f -N -L 10391:10.10.48.216:10391 172.16.58.3<file_sep>/Tools/Utilities/aws.sh #!/bin/bash #This script perform following operations on your AWS instance #Status check #Start instance #Stop instance #Update /etc/hosts file with your AWS instance information SSH_KEY='~/.ssh/sanju.pem' USERNAME='sanjeev-basis' # Hard code this value for status command to work if running the script from a host where username will be different from your username HostFile='/etc/hosts' YELLOW='\033[1;33m' NC='\033[0m' # No Color #prints command usage usage() { if [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux printf '\n Usage: ${0} [-start] [-stop] [-status] [-setup] \n' >&2 printf ' -start <instance-name> Start the AWS instance. \n' >&2 printf ' -stop <instance-name> Stop the AWS instance \n' >&2 printf ' -stopAll Stop all of your AWS instances \n' >&2 printf ' -status [OPTIONAL] <instance-name> Status of the AWS instance \n' >&2 printf ' -setup <your-name> Updates /etc/hosts file with your AWS instances \n' >&2 printf ' <your-name> == Owner TAG on your AWS instances \n' >&2 fi if [[ "$OSTYPE" == "darwin"* ]]; then # Mac OSX echo "\n Usage: ${0} \033[33;5;7m [-start] [-stop] [-status] [-setup] \033[0m " >&2 echo "\033[33;5;7m\n-start <instance-name>\033[0m Start the AWS instance." >&2 echo "\033[33;5;7m\n-stop <instance-name>\033[0m Stop the AWS instance" >&2 echo "\033[33;5;7m\n-stopAll \033[0m Stop all of your AWS instances" >&2 echo "\033[33;5;7m\n-status [OPTIONAL] <instance-name>\033[0m Status of the AWS instance" >&2 echo "\033[33;5;7m\n-setup <your-name>\033[0m Updates /etc/hosts file with your AWS instances" >&2 echo " <your-name> == Owner TAG on your AWS instances \n" >&2 exit 1 fi } log() { if [[ "$OSTYPE" == "linux-gnu" ]]; then printf "\n ${YELLOW}$1${NC} \n\n" # Linux fi if [[ "$OSTYPE" == "darwin"* ]]; then echo "\033[33;5;7m\n $1 \n\033[0m" # Mac OSX fi } if [[ $# -gt 2 ]] then log 'Invalid arguments !!' usage fi ARG=$2 # Function to check the status of the AWS instance status(){ if [[ $ARG < 1 ]] then echo "Querying status on all of your AWS instances...." for i in $(aws --output json ec2 describe-instances --filters "Name=tag:owner,Values=$USERNAME" | grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ","); do echo "$(aws --output text ec2 describe-instances --instance-id $i | grep TAGS | grep name | awk '{print $3 " ==> "}' | tr -d '\n')$(aws --output text ec2 describe-instances --instance-id $i | grep -w STATE | awk '{print $3}')" done elif [[ $ARG > 1 ]] then HOSTNAME=$ARG AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $3}') PUBLIC_AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $2}') INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") if [[ -z "${AWS_HOSTNAME// }" ]] then log 'Host not found in /etc/hosts file. Please verify the hostname' exit 1 fi echo "Querying status of <$ARG> instance" #INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") STATUS=$(aws --output text ec2 describe-instance-status --instance-ids $INSTANCE_ID | sed -n '2p' | awk '{print $3}') if [[ $STATUS = 'running' ]] then log 'Instance is running' else log 'Instance is not running' fi fi } # Function to start the AWS instance start(){ if [[ $ARG < 1 ]] then log 'Please provide instance name' usage exit 1 fi HOSTNAME=$ARG AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $3}') PUBLIC_AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $2}') INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") NAME_TAG=$(aws --output text ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" | grep TAGS | grep name | awk '{print $3}') if [[ -z "${AWS_HOSTNAME// }" ]] then log 'Host not found in /etc/hosts file. Please verify the hostname' exit 1 else #INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") STATUS=$(aws --output text ec2 describe-instance-status --instance-ids $INSTANCE_ID | sed -n '2p' | awk '{print $3}') if [[ $STATUS = 'running' ]] then log 'Instance is already running' exit 1 fi fi #INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") echo "\nStarting: \033[33;5;7m $INSTANCE_ID --> ($NAME_TAG) \033[0m" aws ec2 start-instances --instance-ids $INSTANCE_ID SSH_EXIT_STATUS=$? if [[ $SSH_EXIT_STATUS -ne 0 ]] then EXIT_STATUS=$SSH_EXIT_STATUS log 'Error in starting the instnace....' else sleep 10 echo "\033[33;5;7m\n $INSTANCE_ID --> ($NAME_TAG) \033[0m started successfully !!" echo "Please login to your instance using the command: ssh -i $SSH_KEY ubuntu@$PUBLIC_AWS_HOSTNAME\n" fi } # Function to stop the AWS instance stop(){ if [[ $ARG < 1 ]] then log 'Please provide name of the instance to stop' usage exit 1 elif [[ $ARG > 1 ]] then HOSTNAME=$ARG AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $3}') PUBLIC_AWS_HOSTNAME=$(cat /etc/hosts | grep -i $HOSTNAME | awk '{print $2}') INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") if [[ -z "${AWS_HOSTNAME// }" ]] then log 'Host not found in /etc/hosts file. Please verify the hostname' exit 1 else #INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") STATUS=$(aws --output text ec2 describe-instance-status --instance-ids $INSTANCE_ID | sed -n '2p' | awk '{print $3}') if [[ -z "${STATUS// }" ]] then log "Instance is already stopped" exit 1 fi fi echo "Stopping your <$ARG> instance...." #INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") aws ec2 stop-instances --instance-ids $INSTANCE_ID SSH_EXIT_STATUS=$? if [[ $SSH_EXIT_STATUS -ne 0 ]] then EXIT_STATUS=$SSH_EXIT_STATUS log 'Error in Stopping the instance....' fi fi } stopAll(){ aws --output json ec2 describe-instances --filters "Name=tag:owner,Values=$USERNAME" |grep "PrivateDnsName" | awk '{print $2}' | sort | uniq | tr -d "\"" | tr -d "," > ~/AWS.txt while read line do AWS_HOSTNAME=$line INSTANCE_ID=$(aws --output json ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" |grep "InstanceId" | awk '{print $2}' | tr -d "\"" | tr -d ",") NAME_TAG=$(aws --output text ec2 describe-instances --filters "Name=private-dns-name,Values=$AWS_HOSTNAME" | grep TAGS | grep name | awk '{print $3}') STATUS=$(aws --output text ec2 describe-instance-status --instance-ids $INSTANCE_ID | sed -n '2p' | awk '{print $3}') if [[ $STATUS = 'running' ]] then echo "Stopping \033[33;5;7m\n $INSTANCE_ID --> ($NAME_TAG)... \033[0m" aws ec2 stop-instances --instance-ids $INSTANCE_ID SSH_EXIT_STATUS=$? if [[ $SSH_EXIT_STATUS -ne 0 ]] then EXIT_STATUS=$SSH_EXIT_STATUS log 'Error in Stopping the instance....' fi else echo "\033[33;5;7m\n $INSTANCE_ID --> ($NAME_TAG) \033[0m already stopped. Skipping to next..." fi done < AWS.txt rm -f AWS.txt log 'All of your AWS instances stopped' } setup(){ echo "\nFinding your AWS instances...." if [[ $ARG < 1 ]] then log 'Please provide the owner tag for your AWS instance' usage exit 1 fi if [[ $ARG > 1 ]] then OWNER=$ARG INSTANCE_FOUND=$(aws --output text ec2 describe-instances --filters "Name=tag:owner,Values=$OWNER") if [[ -z "${INSTANCE_FOUND// }" ]] then log 'No AWS instances found with supplied owner tag. Please verify the tag' exit 1 else NUM_INSTANCES=$(aws --output json ec2 describe-instances --filters "Name=tag:owner,Values=$OWNER" | grep "PrivateIpAddress" | awk '{print $2}' | tr -d "\"" | tr -d "," | tr -d "[" | sort | uniq | sed '/^\s*$/d' | wc -l) aws --output json ec2 describe-instances --filters "Name=tag:owner,Values=$OWNER" |grep "PrivateDnsName" | awk '{print $2}' | sort | uniq | tr -d "\"" | tr -d "," > ~/AWS.txt while read line do HOSTNAME=$line HOST_IP=$(echo ${HOSTNAME%%.*} | sed -e 's/ip-//' -e 's/-/./g') NAME_TAG=$(aws --output text ec2 describe-instances --filters "Name=private-dns-name,Values=$HOSTNAME" | grep TAGS | grep name | awk '{print $3}') HOST_IN_ETC=$(grep $HOSTNAME $HostFile) if [[ -z "${HOST_IN_ETC// }" ]] then sudo bash -c "echo $HOST_IP $HOSTNAME $NAME_TAG >> /etc/hosts" else echo "\033[33;5;7m\n $HOSTNAME \033[0m alreasy exists in /etc/hosts file. skipping..." fi done < AWS.txt rm -f AWS.txt fi fi } case "$1" in #start the AWS instance 'start') start ;; 'stop') #stop the AWS instance stop ;; 'stopAll') #stop the AWS instance stopAll ;; 'status') #Query the status on the AWS instance status ;; 'setup') # Updates /etc/hosts file with your AWS instance IP/HOSTNAME setup ;; #prints command usage in case of bad arguments *) usage ;; esac exit $EXIT_STATUS
3f92a28011d9bcf6500c6148edef0b513fd233e0
[ "Shell" ]
2
Shell
rajansanthanam/support
6b66b255db0972bf448c05bc818d91719c26208f
318e319014c97c4e4d9c61e50116d35266e7cb0f
refs/heads/master
<file_sep># exe would like to turn the python app into exe <file_sep>from tkinter import * import tkinter from tkinter import messagebox def proces(): number1 =Entry.get(E1) number2 =float(number1)/3 number3 =float(number1)/3 number4 =float(number1)/3 Entry.insert(E2,0,number2) \ Entry.insert(E3,0,number3) Entry.insert(E4,0,number4) print(number2) print(number3) print(number4) top = tkinter.Tk() L1 = Label(top, text="RENT",).grid(row=0,column=1) L2 = Label(top, text="Value",).grid(row=1,column=0) L3 = Label(top, text="Ju",).grid(row=2,column=0) L4 = Label(top, text="Pe",).grid(row=3,column=0) L5 = Label(top, text="Lu",).grid(row=4,column=0) E1 = Entry(top, bd =5) E1.grid(row=1,column=1) E2 = Entry(top, bd =5) E2.grid(row=2,column=1) E3 = Entry(top, bd =5) E3.grid(row=3,column=1) E4 = Entry(top, bd =5) E4.grid(row=4,column=1) B=Button(top, text ="Submit",command = proces).grid(row=5,column=1,) top.mainloop()
44348a089d64c60f857c885b4387e37d674f2979
[ "Markdown", "Python" ]
2
Markdown
lucmat/exe
084894964a02d223012df22408a024d2900d27cd
04fe507129c66f7900bcd93c291a59f6119e8497
refs/heads/master
<repo_name>Jonathan-Eboh/WebDevelopment<file_sep>/Python/Learning_Python/Django_Projects/login_Reg/apps/logNReg/views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from .models import User import bcrypt from django.urls import reverse # Create your views here. def index(request): return render(request, "logNReg/index.html") # return render(request, "logNReg/index.html") def register(request): register_check = User.userManager.validateReg(request.POST['firstname'], request.POST['lastname'],request.POST["email"], request.POST['password'], request.POST['password_confirm']) if register_check == False: messages.error(request, "Invalid Registration Information") return redirect('/') else: messages.success(request, "Successful Registration") #if they make it here they are already in the database because that is handeled in the models request.session["current_user"] = register_check["True"] #this means the the user is now logged int return redirect('/success/{}'.format(request.session['current_user']))#taking the returned id and placing it in the url def login(request): login_check = User.userManager.login(request.POST['logEmail'],request.POST['logPassword']) if login_check == False: messages.error(request, "Invalid Login Input") return redirect('/') else: messages.success(request, "Successful Login!") request.session['current_user'] = login_check['True'] return redirect('/success/{}').format(request.session['current_user']) def success(request, id): context = { 'user': User.userManager.filter(id=id)[0] } return render(request, "logNReg/success.html", context) <file_sep>/Python/Learning_Python/Flask_MySQL/DB_Connection/server.py from flask import Flask # import the Connector function from DBconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'world') # an example of running a query print mysql.query_db("SELECT * FROM cities") app.run(debug=True) <file_sep>/MEAN/message_board/messageBoard.js 'use strict' //This is the sever set up file //So the app.use and app.set things go in here as well as our const and requirments // Always start with your server.js file // The server.js file acts as the home base for your application. This is where you require the routes and the mongoose configurations // The server.js also creates the express application, loads configurations onto it, and then tells it to listen! // Require the Express Module const express = require('express'); // Require body-parser (to receive post data from clients) const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const path = require('path'); // Create an Express App let app = express(); // Integrate body-parser with our App app.use(bodyParser.urlencoded({ extended: true })); // Setting our Static Folder Directory app.use(express.static(path.join(__dirname, './client/css'))); // Setting our Views Folder Directory app.set('views', path.join(__dirname, './client/views')); // Setting our View Engine set to EJS app.set('view engine', 'ejs'); require("./server/config/mongoose_setup.js"); let route = require('./server/config/routes.js')(app); app.listen(8000, function() { console.log("listening on port 8000"); }) <file_sep>/Python/Make_Change.py def change(cents): coins = {} ... return coins <file_sep>/MEAN/mongoose_dashboard/routes/index.js 'use strict' //Our routes will go in this file this time around module.exports = function Route(app){ const mongoose = require('mongoose'); let AnimalSchema = new mongoose.Schema({ name: String, //These two field are kinda like the SQL fields CHARfield weight: Number// and INTfield respectively }) mongoose.model('Animal', AnimalSchema); // We are setting this Schema in our Models as 'User' let Animal = mongoose.model('Animal') // We are retrieving this Schema from our Models, named 'User' // Routes // Root Request app.get('/', function(req, res) { //This is where we will display all the Mongooses Animal.find({},function(err,animals_found) { console.log(animals_found); if (err) { console.log("Mongooses were unable to be displayed"); }else { console.log("Mongooses were successfully displayed"); //Need to change where this line of code and logic check is placed in this project res.render('index', {fetched_animals: animals_found}); //passing the fetched_animals dictionary //The fetched_animals key IS the name for our animals_found array. It is the name of the pointer to our array } }); }) app.get('/animals/new', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. Animal.find({},function(err,animals_found) { if (err) { console.log("New mongoose unable to be generated"); }else { console.log("Lets make a new mongoose!!!"); //Need to change where this line of code and logic check is placed in this project res.render('newGoose', {fetched_animals: animals_found}); //passing the users_found dictionary } }); }) app.get('/animals/:id', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. Animal.findOne({_id: req.params.id},function(err,animals_found) { if (err) { console.log("New mongoose unable to be generated"); }else { console.log("Lets make a new mongoose!!!"); //Need to change where this line of code and logic check is placed in this project res.render('singleGoose', {fetched_animals: animals_found}); //passing the users_found dictionary //{single_animal: animals_found} } }); }) app.get('/animals/:id/edit', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. Animal.findOne({_id: req.params.id},function(err,animals_found) { if (err) { console.log("New mongoose unable to be generated"); }else { console.log("Lets make a new mongoose!!!"); //Need to change where this line of code and logic check is placed in this project res.render('editGoose', {fetched_animals: animals_found}); //passing the users_found dictionary //{single_animal: animals_found} } }); }) app.post('/animals/:id', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. Animal.update({_id: req.params.id},{name: req.body.newName, weight: req.body.newWeight}, function(err,animals_found) { if (err) { console.log("New mongoose unable to be generated"); }else { console.log("Lets make a new mongoose!!!"); //Need to change where this line of code and logic check is placed in this project res.redirect('/'); // } }); }) app.post('/animals/:id/destroy', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. Animal.remove({_id: req.params.id}, function(err,animals_found) { if (err) { console.log("New mongoose unable to be generated"); }else { console.log("Lets make a new mongoose!!!"); //Need to change where this line of code and logic check is placed in this project res.redirect('/'); // } }); }) // Add User Request app.post('/animals', function(req, res) { console.log("POST DATA", req.body); // This is where we would add the user from req.body to the database. // create a new User with the name and age corresponding to those from req.body let animals = new Animal({name: req.body.name, weight: req.body.weight}); //white matches the keys in the schema the last one(red) matches the html // Try to save that new user to the database (this is the method that actually inserts into the db) and runs a callback function with an error (if any) from the operation. animals.save(function(err,animals) { // if there is an error console.log that something went wrong! if (err) { console.log("Mongoose was unable to be saved to the database"); }else { // else console.log that we did well and then redirect to the root route console.log("Mongoose successfully saved to database"); } }) res.redirect('/'); }) } <file_sep>/readme.md Contains the contents of the project and excercises gone through while learning Webdevelopment <file_sep>/Python/Learning_Python/Django_Projects/randomWordGenerator/apps/randomWord/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), #redirects to the landing page url(r'^random$', views.random), #redirects to the random method in views.py ] <file_sep>/Python/Learning_Python/Django_Projects/t_buddy/apps/travel_buddy/views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from django.core.urlresolvers import reverse # from .models import User, Quote, Favorite!!!!!!!!!!! # Create your views here. #Our landing page with out login form def index(request): return render(request, 'travel_buddy/index.html') #Our function to listen out for and process the user submitted data from the login form #Will redirect to the landing page on sucessful register def register(request): return redirect(reverse('index')) #upon sucessfully loging in the user will be brought to the dashboard through this route def login(request): return redirect(reverse('dashboard')) #The "home page" for this project upon sucessful login the user will be brought to this page def dashboard(request): return render(request, 'travel_buddy/dashboard.html') #This funciton will ultimately bring us to our Add Plan page were we will #allow the user to specify addtiional plans as well as details about those plans def add_plan(request): return render(request, 'travel_buddy/add_plan.html') def create_plan(request): print "cat" , "*" * 50 return redirect(reverse('add_plan')) #This will be our page were we display the information given to us from add try as well as #displaying the other users who have decided to join on a given trip def destination(request): return render(request, 'travel_buddy/destination.html') <file_sep>/MEAN/hello_express/server.js 'use strict' const express = require("express"); //This preps our server to use the body-parser module const bodyParser = require("body-parser"); const session = require('express-session'); let app = express(); app.get('/', function(req, res) { res.render('index', {title: "my Express project"});// This line allows us to change what our home page renders }) //I changed 'index' to 'index.ejs' and nothing happened? what does that string need to be (if anything) //in order for everything to work properly? app.get("/users", function (req, res){ // hard-coded user data let users_array = [ {name: "Michael", email: "<EMAIL>"}, {name: "Jay", email: "<EMAIL>"}, {name: "Brendan", email: "<EMAIL>"}, {name: "Andrew", email: "<EMAIL>"} ]; res.render('users', {users: users_array}); }) //users/:id //where :id is the id of a particular user. HTTP method is GET app.get("/users/:id", function (req, res){ console.log("The user id requested is:", req.params.id); // just to illustrate that req.params is usable here: res.send("You requested the user with id: " + req.params.id); // code to get user from db goes here, etc... }); //This line is responsible for our servers ability to use the "/static" folder for static content app.use(express.static(__dirname + "/static")); //This line is where we tell our server to utilize the body-parser module app.use(bodyParser.urlencoded({extended: true})); app.use(session({secret: 'codingdojorocks'})); //The string here is for encryption //now, within any of the routes, there will be an object called req.session. It is an object and we can assign properties to it like normal //This line sets the location where express will look for the ejs views app.set('views',__dirname + '/views'); //This line sets the view engine itself so that express knows that we are using ejs as opposed to another templating engine like jade app.set('view engine', 'ejs'); // route to process new user form data: app.post('/users', function (req, res){ console.log("POST DATA \n\n", req.body) req.session.name = req.body.name; //And now req.session.name will be available to any other route afterward. console.log(req.session.name); //code to add user to db goes here! // redirect the user back to the root route. res.redirect('/') }); app.listen(8000, function() { console.log("listening on 8000"); }) //m-muh dependencies... // { // "dependencies": { // "body-parser": "^1.13.3", // "ejs": "^2.3.3", // "express": "^4.13.3", // "socket.io": "^1.3.6" // } // } <file_sep>/MEAN/ANGULAR/test_one/client/js/factories/questions_factory.js app.factory("questionFactory", ['$http', function($http) { //the $http that is passed into the fuction here must match the name of the $http that we use throughout the rest of the file eg ($http.get) let factory = {}; let questions = []; // let loggedUser = ""; factory.login = function(user,callback) { console.log("factory created USER", user); $http.post('/user', user).then(function (userData) { callback(userData.data); console.log("This is a data object", userData.data); }) } factory.showUser = function(callback) { $http.get('/questions').then(function (userData) {//promise callback(userData.data); }) }, factory.showQuestions = function(callback) { $http.get('/questions').then(function (all_questions) {//promise callback(all_questions.data); }) }, factory.createQuestion = function(new_q,callback) { console.log("factory new_q", new_q); $http.post('/questions', new_q).then(function (created_q) { callback(created_q); }) } return factory; }]); <file_sep>/Python/Learning_Python/Django_Projects/randomWordGenerator/apps/randomWord/views.py from django.shortcuts import render, redirect from random import choice, randint from string import ascii_uppercase # Create your views here. def index(request): if "count" not in request.session: #sessions are dictionaries in python so you can operate on them as such request.session['count'] = 0 else: request.session['count'] += 1 return render(request, "randomWord/index.html") def random(request): randomNumber = randint(1, 14) if request.GET['generate'] == 'Reset': request.session.clear() else: request.method == "GET" request.session['generate'] = (''.join(choice(ascii_uppercase) for i in range(randomNumber))) return redirect('/') # if request.method == "POST" # print request.POST # print request.method # request.session['name'] = request.POST['first_name'] # return redirect("/") # else: # return redirect("/") <file_sep>/Python/Learning_Python/Django_Projects/disappearing_ninjas/apps/disNinja/views.py from django.shortcuts import render, redirect def index(request): return render(request, "disNinja/index.html") def all_ninjas(request): return render(request, "disNinja/ninjas.html" ) def one_ninja(request, color): if color == "red": img = 'raph.jpg' elif color == "blue": img = 'leo.jpg' elif color == "orange": img = 'mike.jpg' elif color == "purple": img = 'don.jpg' else: img = 'fox.jpg' context = {'img': img} return render(request, 'disNinja/ninja.html', context) <file_sep>/Python/Learning_Python/Flask_MySQL/fullfriends/server.py from flask import Flask, render_template, request, redirect, url_for from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'fullfriends')#named after database @app.route('/')# This route is to display informaiton in paragraph 1 def index(): #can name this whatever, convention to name landing page index friends = mysql.query_db("SELECT * FROM friends") print friends return render_template('index.html', friends=friends)#the orange friends pairs with the jinja in the html doc({{ friends }}) #the value of the orange friends is set as the content recived form the html call on line 9 # THIS IS THE ROUTE TO CREATE A NEW FRIEND @app.route('/friends', methods=['POST']) def create(): query = "INSERT INTO friends(first_name, last_name, email, created_at, updated_at)\ VALUES(:first_name, :last_name, :email, NOW(), NOW())" # ":" are just placeholders for future values. They have to be equal to the key name in the bottom. NOW is a function (we don't chang it) data= { 'first_name':request.form['first_name'], #we're passing the column name from database 'last_name':request.form['last_name'], 'email':request.form['email'], } mysql.query_db(query, data) #method from a class in mysqlconnection.py return redirect('/') # THIS IS THE ROUTE TO RETRIEVE THE ID AND RERENDER TO THE EDIT PAGE @app.route('/friends/<friend_id>/edit', methods=['GET']) def edit(friend_id): query = "SELECT * FROM friends WHERE id = :id" data = { 'id': friend_id } myvar = mysql.query_db(query, data) return render_template("edit.html", friend=myvar) # THIS IS THE ROUTE TO UPDATE OUR RETRIEVED ID AND ITS RESPECTIVE KEYS AND VALUES BY TAKING USER INPUT FROM THE FORM @app.route('/friends/<friend_id>', methods=['POST']) def update(friend_id): query = "UPDATE friends \ SET first_name = :first_name, last_name = :last_name, email = :email, updated_at=NOW() \ WHERE id = :id" #this is giving up trouble the id is empty and there is no 0 id data= { 'first_name':request.form['first_name'], 'last_name':request.form['last_name'], 'email':request.form['email'], 'id': friend_id } mysql.query_db(query,data) return redirect('/') @app.route('/friends/<friend_id>/delete', methods=['POST']) def destroy(id): print "PENISFACEFUCKOFF" return redirect('/') app.run(debug=True) <file_sep>/MEAN/function_builder.js function runningLogger() { console.log("I am running!"); } runningLogger(); //---------------------- function multiplyByTen(num) { return num * 10; } console.log(multiplyByTen(5)); //---------------------- function stringReturnOne() { console.log("String one!"); return "return one"; } function stringReturnTwo() { console.log("String two!"); return "return_two"; } // stringReturnOne(); // stringReturnTwo(); //---------------------------- function caller(param) { if (typeof(param) === 'function'){ param(); } } // caller(runningLogger()); //----------------------------------------- //The code below prints out the result of the function as well as what it returns //Do we want it to just print the return? function myDoubleConsoleLog(param1, param2) { if (typeof(param1) === 'function' && typeof(param2) === 'function'){ console.log(param1()); console.log(param2()); } } // myDoubleConsoleLog(stringReturnOne, stringReturnTwo); //----------------------------------- function caller2(param) { console.log("Starting..."); var wait = setTimeout(function(){ if (typeof(param) == "function") { param(); } }, 10000); console.log("Ending...?"); return "Interesting!"; } /* var wait; setTimeout wait = setTimeout(function(){ if (typeof(param) == "function") { param(); } }, 2000); console.log("Starting..."); console.log("Ending...?"); */ caller2(myDoubleConsoleLog(stringReturnOne(), stringReturnTwo())); <file_sep>/MEAN/ANGULAR/try_two/server.js //Require all the things we need const express = require("express"); const path = require("path"); const bp = require("body-parser"); const session = require("express-session"); let app = express(); //use body-parser and tell it to return data in JSON format app.use(bp.json()); //accessing our client and bower_components app.use(express.static(path.join(__dirname + "/client"))); app.use(express.static(path.join(__dirname + "/bower_components"))); //enableing us to utilize session app.use(session({ secret: "This is a secret", resave: false, saveUninitialized: true, })); //Allowing us to use our routes as a function that we exported from that file and require here require('./server/server_config/mongoose.js'); require('./server/server_config/routes.js')(app); app.listen(8000, function() { console.log("listening on port 8000"); }); <file_sep>/MEAN/ANGULAR/test_one/client/js/app.js let app = angular.module("myApp", ['ngRoute']); app.config(function ($routeProvider) { // $routeProvider .when('/',{ templateUrl: 'static/partials/login.html' }) .when('/dashboard',{ templateUrl: 'static/partials/dashboard.html' }) .when('/new_question', { templateUrl: 'static/partials/question.html' }) .when('/question/:id', { templateUrl: 'static/partials/QA.html' }) .when('/question/:id/new_answer', { templateUrl: 'static/partials/answer.html' }) .otherwise({ redirectTo: '/' }); }); <file_sep>/MEAN/ANGULAR/try_two/server/server_controllers/serv_users.js //This is the serverside controller for our users let mongoose = require('mongoose'); let newUser = mongoose.model('User'); // This will be our final step of the login process where we finally communicate with the database function userController() { this.login = function(req, res) { newUser.findOne({name: req.body.name}, function(err, result) { if(!result){ newUser.create(req.body, function(err, user) { if (err) { console.log(err); res.json(err); }else{ req.session.user = user; req.session.save(); //This is where the user is being saved to the database console.log("saved user to database 1"); res.json(user); } }); }else { if(err){ res.json(err); } else { req.session.user = result; req.session.save(); console.log("saved user to database 2"); res.json(result); } } }); }; this.index = function(req, res) { if (!req.session.user || req.session.user === null) { res.json({status: false}); } else { res.json(req.session.user); } }; this.logout = function(req, res) { req.session.destroy(); res.redirect("/"); }; } module.exports = new userController(); <file_sep>/Python/TryPython.py animal = "python" animal = "dog" print animal print 2+5 word1 = "Hello" word2 = "World!" print word1 + word2 num = 10 word3 = "ten" print word3 + str(num) <file_sep>/MEAN/ANGULAR/full_mean_friends/server.js const express = require('express');// we use this for all of our http traffic const path = require('path'); const bp = require('body-parser'); let app = express(); <file_sep>/MEAN/nodemonTest/test.js console.log("I am running from node"); console.log("Some changes!"); <file_sep>/Python/Fun_with_functions.py # Odd/Even: # Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number. # def odd_even(): # number = 0 # for i in range(0,2001): # if i % 2 == 0: # print "Number is " +str(i)+" This is an even number." # if i % 2 != 0: # print "Number is " +str(i)+" This is an odd number." # return # # odd_even() # Multiply: # Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5. # # The function should multiply each value in the list by the second argument. For example, let's say: def multiply(x,y): myList =[] #dont forget this for num in x: num*=y myList.append(num) return myList a = [1,2,3,4,5,6] print multiply(a,5) def layered_multiples(arr): newArr = [] for i in arr: newArr.append([1]*i) #you can multiply strings as well as list in python to get multiples of that list return newArr print layered_multiples(multiply(a,5)) <file_sep>/Algorithms/CTCI-Big_O_examples.py 1) #Has runtime O(N) iterating through the array twice doesnt matter because we drop constants #so its not 2(O(N)) def arr_run(arr): int_sum = 0 product = 1 for i in range(len(arr)): int_sum += arr[i] for j in range(len(arr)): product *= arr[j] print str(int_sum)+" , "+str(product) myList =[1,2,3,4,5] arr_run(myList) <file_sep>/Python/Learning_Python/Django_Projects/Many_To_Many/apps/manyToMany/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^add_user$', views.add_user, name="addUser"), url(r'^showResults$', views.show_results, name="showResults"), url(r'^showinterest/(?P<id>\d+)$', views.show_interest, name="showInterest"), url(r'^deleteInterest/(?P<id>\d+)$', views.delete_interest, name="deleteInterest"), url(r'^deleteUser/(?P<id>\d+)$', views.delete_user, name="deleteUser"), url(r'^', views.index, name="index"), ] <file_sep>/MEAN/creating_objects_one.js 'use strict' function literalConstructor(name, age){ let person = {}; //object literal person.name = name; person.age = age; return person; //object literal } let person = literalConstructor(); function instanceConstructor(name, age){ this.name = name; this.age = age; return this; //dont need to return the "this" keyword there because the "new" keyword does that implicitly } let person2 = new instanceConstructor(); //--------------------------------------------- //How to do this is javascript using object literals function VehicleConstructor(name,numWheels,numPassengers) { let vehicle = {};//object literal vehicle.name = name; vehicle.numWheels = numWheels; vehicle.numPassengers = numPassengers; vehicle.makeNoise = function () { console.log("LOUD NOISES!!!"); } return vehicle;//returns object literal } let fastCar = VehicleConstructor("Hot Rod",4,2); fastCar.makeNoise(); console.log(fastCar.name); console.log(fastCar.numWheels); console.log(fastCar.numPassengers); //------------------------------------------------ //JavaScript OOP method of doing this function VehicleInstanceConstructor(name, numWheels, numPassengers, speed) { //speed new here let distance_travelled = 0; //private variable this new too let updateDistanceTravelled = function () { //new distance_travelled += speed; console.log("The distance you have travelled so far is " + distance_travelled); } //Public variable this.name = name; this.numWheels = numWheels; this.numPassengers = numPassengers; this.speed = speed; //new this.makeNoise = function () { console.log("LOUDER NOISES!!!"); } this.move = function () { //new as well updateDistanceTravelled(); this.makeNoise(); } this.checkMiles = function () { //new console.log(distance_travelled); } return; } //USEING A PROTOTYPE---------------------------------------------------------- VehicleInstanceConstructor.prototype.generateVIN = function () { console.log("The VIN number for your "+ this.name + " is : " + Math.floor(((Math.random() * (10000000000000000 - 0 + 1)) + 0))); return this; } let fastCar2 = new VehicleInstanceConstructor("Hotter Rod", 4, 2,60); fastCar2.makeNoise(); console.log(fastCar2.name); console.log(fastCar2.numWheels); console.log(fastCar2.numPassengers); // console.log(fastCar2.speed,"cat"); fastCar2.move(); fastCar2.checkMiles(); fastCar2.generateVIN(); //ENVOKING THE PROTOTYPE--------------------------------- //------------------------------------------------------ //BIKE let bike = new VehicleInstanceConstructor("Nice Bike",2,1,10); bike.makeNoise = function () { console.log("Ring Ring"); }; bike.makeNoise(); console.log(bike.name); console.log(bike.numWheels); console.log(bike.numPassengers); bike.generateVIN(); //------------------------------------------------------ //SEDAN let sedan = new VehicleInstanceConstructor("Sedan", 4, 2,50); sedan.makeNoise = function () { console.log("Honk Honk"); }; sedan.makeNoise(); console.log(sedan.name); console.log(sedan.numWheels); console.log(sedan.numPassengers); sedan.generateVIN(); //------------------------------------------------------ //BUS let bus = new VehicleInstanceConstructor("bus", 4, 2,20); bus.makeNoise = function () { console.log("LOUD BUS NOISES!"); }; bus.makeNoise(); bus.pickUp = function (passengers) { this.numPassengers += passengers; console.log("This bus now has " + this.numPassengers + " onboard!"); } bus.pickUp(5); console.log(bus.name); console.log(bus.numWheels); console.log(bus.numPassengers); bus.pickUp(2); bus.generateVIN(); // console.log(Math.floor(((Math.random() * (10000000000000000 - 0 + 1)) + 0))); // console.log(Math.floor(((Math.random() * (10000000000000000 - 0 + 1)) + 0))); // console.log(Math.floor(((Math.random() * (10000000000000000 - 0 + 1)) + 0))); // console.log(Math.floor(((Math.random() * (10000000000000000 - 0 + 1)) + 0))); <file_sep>/MEAN/ANGULAR/test_one/server/config/routes.js const questions = require('../controllers/questions_controller.js'); module.exports = function (app) { app.post('/user', function(req, res){ questions.user(req, res); }) //Place all the server side routes here. These are the routes that talk to the factories app.get('/questions',function(req, res) { questions.index(req,res); }) app.post('/questions',function(req, res) { console.log('server-routes'); questions.create(req,res); }) } <file_sep>/Python/Learning_Python/Django_Projects/survey_form/apps/surveyForm/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), # redirects to the landing page url(r'^result$', views.result),#redirects to success route url(r'^success$', views.success)#redirects to the results page ] <file_sep>/MEAN/ANGULAR/product_factory/productFactoryOrdersController.js 'use strict' myAppModule.controller('ordersController', [ '$scope', 'productFactory', function($scope, productFactory) { function setProducts(data) { $scope.products = data; $scope.product = {}; } $scope.products = []; productFactory.index(setProducts); $scope.buy = function(id) { productFactory.buy({ id: id, quantity: 1 }, setProducts); } } ]); <file_sep>/Algorithms/The Basic 13-pg27.js //1) print 1-255 // for (var i = 1; i <= 255; i++) { // console.log(i); // } //2)print odds 1-255 //3)Print Ints and Sum 0-255 //4)Interate and print Array //5)find and print Max //6)get and print Average //7)array with odds // function arrayWithOdd() { // var arr = []; // for (var i = 1; i < 255; i+=2) { // if (i % 2 !== 0) { // arr.push(i); // } // } // return arr; // } // // console.log(arrayWithOdd()); //8) square the values // function squared(arr) { // for (var i = 0; i < arr.length; i++) { // arr[i]*=arr[i]; // } // return arr; // } // // console.log(squared([2,4,6])); //9)Greater than Y // // function greaterThanY(arr,y) { // var count = 0; // for (var i = 0; i < arr.length; i++) { // if (arr[i]>y) { // count+=1; // } // // } // return count; // } // // console.log(greaterThanY([1,2,3,4,5,6],2)); //10)Zero out negative numbers // function toZero(arr) { // for (var i = 0; i < arr.length; i++) { // if (arr[i]<0) { // arr[i] = 0; // } // } // return arr; // } // console.log(toZero([-3,-2,-1])); //11)Min Max Average //12)Shift Array values // function shiftOne(arr) { // for (var i = 0; i < arr.length-1; i++) {// note that we end at the index before the last one in the array // arr[i]= arr[i+1]; // } // arr[arr.length-1]=0; // return arr; // } // ///This is much more simple than I made it out to be lol // console.log(shiftOne([1,2,3,4])); //13)Swap String For Array Negtive values // function swapString(arr) { // for (var i = 0; i < arr.length; i++) { // if (arr[i]<0) { // arr[i]="Dojo"; // } // } // return arr; // } // // console.log(swapString([-1,-2,-3])); <file_sep>/MEAN/ANGULAR/try_two/client/assets/app.js //our client side routing will go in this file let app = angular.module('app', ['ngRoute']); //we name our app here and make sure we are calling ngRoute app.config(function($routeProvider) { $routeProvider .when('/login',{ //This will act as our landing page templateUrl: 'partials/login.html', controller: 'userController' }) .when('/dashboard',{ //This will act as our landing page templateUrl: 'partials/dashboard.html', controller: 'dashboardController' }) .when('/ask', { templateUrl: 'partials/ask.html', controller: 'questionController' }) .otherwise({ redirectTo: 'login' //This makes it seem as though our login page is our landing page to our user even though we dont make our index page our landing page }); }); <file_sep>/Python/Python_OOP_Chaining_Methods.py class Bike(object): def __init__(self, price,max_speed,miles=0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print self.price, self.max_speed, self.miles return self def ride(self): print "Riding" self.miles += 10 #if you want to alter the class variable be sure to access and chage that variable and not the instance variable print self.miles return self def reverse(self): print "Reversing" if self.miles >= 5: self.miles -= 5 return self else: print "You cant have negative miles!" return self bike1 = Bike(100,20,60) bike1.ride().ride().ride().reverse().displayInfo() bike2 = Bike(200,30,0) bike2.ride().ride().reverse().reverse().displayInfo() bike3 = Bike(150,25,0) bike3.reverse().reverse().reverse().displayInfo() <file_sep>/MEAN/message_board/server/config/routes.js // This is the file that specifies which routes will be handled and by which controller methods. // From routes.js we require the controller file (or files). // const mongoose = require('mongoose'); // const Message = mongoose.model('Message');// preemtivly naming our schema model that will be made in Message.js const postsController = require("./../controllers/posts.js")//walks us up and over to posts and grabs that whole file const commentsController = require("./../controllers/comments.js")//walks us up and over to comments and grabs that whole file module.exports = function (app) { //root route app.get('/', postsController.getAllMessagesWithComments); //This renders our landing page app.post('/message', postsController.postMessage); //This routes to where we process the message added by the user and subsequently route them back to the landing page app.post('/comment/:id', commentsController.createComment);//This is the route by which we create one comment with the parent post id } <file_sep>/Python/Learning_Python/Django_Projects/Many_To_Many/apps/manyToMany/views.py from django.shortcuts import render, redirect from django.contrib import messages from .models import User, Interest from django.urls import reverse #index def index(request): return render(request, "manyToMany/index.html") def add_user(request): if request.method != "POST": return redirect(reverse("index")) else: if User.userManager.validateUser(request.POST): print "Went through", "*" * 50 return redirect(reverse("showResults")) else: print "Did not go through", "-" * 50 return redirect(reverse("index")) #showResults def show_results(request): #whenever we want to make availible, the information we are manipilating we pass it to a function in the from of a dictionary then pass that to what the function renders print "cat" context = { "users" : User.userManager.all() #in particular we are passing all of the data associated with our User class } print context return render(request, "manyToMany/results.html", context) #showInterest def show_interest(request,id): #needs to take id because we are going to show the interest of a specific user user = User.userManager.filter(id = id) context = { "profile" : user[0].interest.all() #all the inerest assoiciated with the specific implicite id field. } return render(request, "manyToMany/interests.html", context) #passing context to the render request gives the given page access to all the information inside of context def delete_interest(request,id): #again we need id because we are trying to preform an action with a specific id Interest.objects.get(id=id).delete() #its ok to use .get here because we know that there is only one of what we are asking for and that it is indeed within our database #So we are grabing the specific user id and then running .delete() on that information #make sure to understand which "id" is which and what each one is doing return redirect(reverse("showResults")) def delete_user(request, id): User.userManager.get(id=id).delete() #similar logic is used to delete a given user return redirect(reverse("showResults")) <file_sep>/MEAN/main.js x = [3,5,"Dojo", "rocks", "Michael", "Sensei"]; for (let i = 0; i < x.length; i++) { console.log(x[i]); } x.push(100); console.log(x); x = ["hello", "world", "JavaScript is Fun"]; console.log(x); let sum = 0; for (let i = 0; i < 500; i++) { sum += i; } console.log(sum); y = [1, 5, 90, 25, -3, 0]; let min = y[0]; let avg = 0; sumY = 0; for (let i = 0; i < y.length; i++) { if (y[i] < min) { min = y[i]; } sumY += y[i]; } avg = sumY/y.length; console.log(min, avg); let newNinja = { name: 'Jessica', profession: 'coder', favorite_language: 'JavaScript', //like that's even a question! dojo: 'Dallas' } for (let key in newNinja){ if (newNinja.hasOwnProperty(key)){ console.log(key); console.log(newNinja[key]); } } <file_sep>/MEAN/ANGULAR/try_two/client/assets/controllers/usersController.js app.controller('userController', ["$scope", "userFactory", "$location", function($scope, userFactory, $location) { //setting up our controller to work with our factory $scope.user = {}; $scope.login = function() { if(!$scope.user.name){ alert("User name can't be blank"); } else { userFactory.login($scope.user, function(returnedData) { console.log("made it to userController .login"); $scope.user = {}; $location.url("/dashboard"); //This brings you to the dashboard on successful login }) } }; }]); <file_sep>/MEAN/ANGULAR/try_two/client/assets/factories/userFactory.js app.factory('userFactory', ['$http', function($http) { //Here we name our factory and utilize $http so that we can pass information around appropriately function UserFactory() { //capital U because it is a constructor let _this = this; //we are going to reference the object itself with this instead of using factory this.login = function(user, callback) { //the user is generated from the form and passed to the controller then passed here $http.post("/login", user).then(function(returnedData) { //this is a promise callback(returnedData.data); console.log("Made it to userFactory .login"); }); }; this.user = function (callback) { //gets the user $http.get('/index').then(function(returnedData) { callback(returnedData); console.log("Made it to userFactory .user"); }); }; } return new UserFactory(); //Cut things down by returning a new instance of the UserFactory }]); <file_sep>/MEAN/message_board/server/models/Comment.js //The schema goes in here // This is the file that specifies the schema to be loaded by mongoose. // This file is required by mongoose.js. // We do not need to require this file in the controller, instead, the model itself is loaded from mongoose. // There can be many models in the server/models folder. //One post can have many comments--------------- //Each comment only belongs to one post--------------- const mongoose = require('mongoose'); let Schema = mongoose.Schema;//Needs to know of the schema let CommentSchema = new mongoose.Schema({ name: {type: String}, comments: {type: String}, _post: {type: Schema.Types.ObjectId, ref: 'Post'}, //underscore because post is a different table }, {timestamp: {createdAt: 'created_at', updatedAt: 'updated_at'} }); CommentSchema.path('name').required(true, 'Name cannot be blank'); CommentSchema.path('comments').required(true, 'Comment cannot be blank'); // set our models by passing them their respective Schemas mongoose.model('Comment', CommentSchema); <file_sep>/MEAN/ANGULAR/prodts_factory/productsFactory.js var app = angular.module('myApp', []); app.factory('productFactory', [ '$http', function($http) { var factory = {}; var products = [ // { // // name: "hat", // // quantity: 50, // // price: 14.99 // } ]; factory.create = function(data, callback) { data.quantity = 50; products.push(data); callback(products); } factory.index = function(callback) { callback(products); } factory.update = function(data, callback) { if (Number.isInteger(data.quantity)) { if (products[data.id].quantity - data.quantity > 0) { products[data.id].quantity -= data.quantity; } else { products[data.id].quantity = 0; } } callback(products); } factory.delete = function(id, callback) { products.splice(id, 1); callback(products); } return factory; } ]) <file_sep>/MEAN/survey_form/routes/index.js 'use strict' //Our routes will go in this file this time around module.exports = function Route(app){ //This is our landing page which renders our index.ejs file app.get('/', function(req, res) { res.render("index"); }) // post route for adding a data from a survey app.post('/result', function(req, res) { // submitted_info = { //1)Here we pass the user information from the form in index.ejs to our session req.session.name= req.body.name; req.session.dojo_location= req.body.dojo_location; req.session.fave_language= req.body.fave_language; req.session.comment= req.body.comment; // }; res.redirect('/success'); //we redirect on post, never render }); app.get('/success', function(request, response){ //This works because all this information has been caught by the session here in our case //2)Now here is where we pass the user information from the session into our javascript object let results_info = { name: request.session.name, dojo_location: request.session.dojo_location, favorite_language: request.session.fave_language, comment: request.session.comment, }; console.log(results_info); //3)This is where we finally make that user information available for rendering response.render("results", {user_data:results_info}) //This is where we make the user entered data available //for us to use. //we store it in a dictionary that has key user_data and a value of a javascript object }); } <file_sep>/MEAN/ANGULAR/test_one/server/controllers/questions_controller.js const mongoose = require('mongoose'); let Question = mongoose.model("Question"); module.exports = ( function() { return{ user: function(req, res){ let receivedUser = new Question(req.body); // console.log(receiveUser); receivedUser.save(function(err, results){ if (err){ console.log(err); res.json(err); } else { res.json(results); } }) }, index: function (req, res) { Question.find({}, function(err, results) { console.log('finding all questions in db...'); if(err){ res.json(err); }else { res.json(results); } }) }, create: function(req, res) { recievedQuestion = new Question(req.body); console.log('sever-controller'); recievedQuestion.save(function(err, results) { if (err) { console.log(err); //good for debugging res.json(err); }else { res.json(results) } }) } } })(); <file_sep>/Python/Learning_Python/Flask_Fundamentals/Hello/server.py # goes with Hello flask assingment from flask import Flask, render_template app =Flask(__name__) @app.route('/success.html') def index(): return render_template('index.html') @app.route('/') def success(): return render_template('index.html', name = "Jon") app.run(debug=True) <file_sep>/Python/Learning_Python/Django_Projects/MAIN/Main/apps/ninja_gold/views.py from django.shortcuts import render, redirect from random import randint as ri # Create your views here. def index(request): if 'log' not in request.session: request.session['log'] = "" if 'gold' not in request.session: request.session['gold'] = 0 return render(request, "ninja_gold/index.html") def process(request): if request.GET['button'] == 'farm': request.session['gold'] += ri(10,21) #renamed randint function at toplist of module elif request.GET['button'] == 'cave': request.session['gold'] += ri(5,11) elif request.GET['button'] == 'house': request.session['gold'] += ri(2,6) elif request.GET['button'] == 'casino': request.session['gold'] += ri(-50,51) return redirect('/') <file_sep>/WebFundamentals/HTML/JavaScript Basics.html <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Basics</title> <meta name="description" content="JavaScript Basics"> <link rel="stylesheet" type="text/css" href="JavaScript Basics.css"> </head> <body> <div class="background"> <div class="topbar"> <h1 class="toptext">Javascript Basics</h1> </div> <div class="bodyblock"> <div class="navbox"> <div class="navigation"> <a class="homelink"href="#">Home</a> <ul class="navlist"> <li><a href="#">startlist</a></li> <li><ul> <li><a href="#">text</a></li> <li><a href="#">more text</a></li> <li><a href="#">more text</a></li> <li><a href="#">more text</a></li> <li><a href="#">more text</a></li> <li><a href="#">more text</a></li> </ul></li> <li><a href="#">text</a></li> <li><a href="#">text</a></li> <li><a href="#">end list</a></li> </ul> <div class="circletest"></div> </div> </div> <div class="linkswrapper" <div class="linksbox"> <h1 class="linkheader">JavaScript Basics</h1> <p class="linkparagraph">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque et aliquam justo, sed pulvinar turpis. Praesent non nisl pellentesque mauris posuere ultricies. Curabitur iaculis ullamcorper enim, malesuada ultrices enim lacinia nec. Aliquam condimentum interdum urna a ultricies. Morbi sollicitudin tempus velit, eu suscipit lorem imperdiet non. Quisque posuere at libero sit amet pharetra. Ut vitae nunc eget mauris rutrum elementum.</p> <ul class="linklist"> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> <li><a href="#">Aliquam vulputate</a>, quam quis suscipit consectetur, tortor arcu dignissim mauris, ac auctor mi ipsum sit amet eros. Vestibulum sit amet enim sit amet risus rhoncus molestie id vel ipsum. Vestibulum enim ex, placerat id ex rutrum, venenatis viverra justo. <q><span class="span">Donec aliquam </span></li></q> </ul> <!-- <div class="links"></div> --> <!-- </div> --> </div> </div> <div class="bottombar"> <p class="bottomtext">Phasellus at elit vitae elit <a href="#">lobortis</a></p> <a href="#"></a> </div> </div> </body> </html> <file_sep>/WebFundamentals/Javascript/For a Few Billion.js /* There is an old tale about a king who offered a servant $10,000 as a reward. The servant instead asked that for 30 days he be given an amount that would double, starting with a penny. (1 penny for the first day, 2 for the second, 4 for the third, then 8, 16, 32 pennies, and so on). Use for loops to answer the following: How much was the reward after 30 days? remember, a penny isn't 1, but 0.01 Bonus (Only If You Have Time): How many days would it take the servant to make $10,000? How about 1 billion? In JavaScript, there is a value Infinity, how many days until the servant has infinite money? */ ///money accumilated untill 10000 var day = 0; for (var i = 0.01; i <= 10000; i*= 2) { if (day === 30) { console.log("Its been 30 days and I currently have" + i + "monies!"); } day+=1; } console.log("It takes " + day + " days to reach 10,000$"); ///it takes 20 days to get to to 10000 dollars._______ var monies = 0.01; for (var i = 2; i <= 30; i++) { monies *= 2; } console.log("After 30 days the slave will have " + monies + "$ in total"); ///after 30 days the slave will have 5368709.12$ dollars in total ////days until a billion dollars is reached var day_2 = 1; for (var i = 0.01; i <= 1000000000; i*= 2) { day_2+=1; } console.log("It takes " + day_2 + " days to reach the billion dollars"); ///days untill servant has infinite money var day_3 = 0; for (var i = 0.01; i <= Infinity; i*= 2) { ///This if just Infinity, at least conceptually day_3+=1; } console.log("It takes " + day_3 + " days to reach the Infinity dollars"); <file_sep>/Python/Learning_Python/Django_Projects/Many_To_Many/apps/manyToMany/migrations/0002_auto_20170227_2107.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-27 21:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('manyToMany', '0001_initial'), ] operations = [ migrations.CreateModel( name='Interest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('interest_name', models.CharField(blank=True, max_length=255, null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.RemoveField( model_name='user', name='Interest', ), migrations.RemoveField( model_name='user', name='name', ), migrations.AddField( model_name='user', name='created_at', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='user', name='updated_at', field=models.DateTimeField(auto_now=True), ), migrations.AddField( model_name='user', name='user_name', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField( model_name='interest', name='user_interest', field=models.ManyToManyField(related_name='interest', to='manyToMany.User'), ), ] <file_sep>/Python/Learning_Python/Django_Projects/Many_To_Many/apps/manyToMany/models.py from __future__ import unicode_literals from django.db import models import re NAME_REGEX = re.compile(r'[a-zA-Z]{2,}') class UserManager(models.Manager): def validateUser(self, postData): status = True errors = [] if not NAME_REGEX.match(postData['name']): # Not (True) is False thus if the conditional evaluates to true then not will make it false and skip the code under it. Otherwise it will evaluate to False and then not will make it true and the code under it will indeed run errors.append("Name field should contain letters only!") status = False if not NAME_REGEX.match(postData['interest']): #similar logic as above, just for interet instead of name status = False if len(postData['name']) < 1: #Make sure the name field isnt blank errors.append("Name field cannot be blank!") status = False #The next portion is important...... if User.userManager.filter(user_name=postData['name']): user = User.userManager.filter(user_name = postData['name']) # This returns a list of one element interest = user[0].interest.all() #im pretty sure this is where we utilize the ManyToManyField by putting all of the users interest into a variable called interest for interest in interests: print interest.interest_name if interest == interest.interest_name: #Check to see if the users interest is already in the database? As in users can have multiple interest just cant input the same one errors.append("User already has that interest") return False else: this_user = User.userManager.get(user_name = postData['name']) this_interest = Interest.objects.create(interest_name = postData['interest']) this_interest.users_interested.add(this_user) #This line is establishing the link between the user and their interest...This should be in the form of a list return True #This next code block is where we actually enter the user and thier interest into the database granted everything else checked out. if status is True: user = User.userManager.create(user_name = postData['name']) interest = Interest.objects.create(interest_name = postData['interest']) #pay attention to this line interest.user_interest.add(user) #This is where we join interest to the user, adding to that list print "we created" return True class User(models.Model): user_name = models.CharField(max_length= 255, blank = True, null=True) userManager = UserManager() #our instance of our UserManager class declared within our User class created_at = models.DateTimeField(auto_now_add=True, blank = True, null = True) updated_at = models.DateTimeField(auto_now=True) class Interest(models.Model): interest_name = models.CharField(max_length=255, blank = True, null=True) user_interest = models.ManyToManyField(User, related_name="interest") #links our tables through a many to many relationship created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) <file_sep>/Python/Multiples_Sum_Average.py # Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use an array to do this exercise. # for num in range(1001): # print num # # mult = 5 # Create another program that prints all the multiples of 5 from 5 to 1,000,000. # while (mult <= 1000000): # print mult # mult+=5 # Create a program that prints the sum of all the values in the list: # a = [1, 2, 5, 10, 255, 3] # # runtot = 0 # for num in a: # runtot+=num # # print runtot # Create a program that prints the average of the values in the list: # a = [1, 2, 5, 10, 255, 3] # # runtot = 0 # # for num in a: # runtot+=num # avg = runtot/len(a) # # print avg <file_sep>/Python/Learning_Python/Django_Projects/main_project/apps/first_app/urls.py from django.conf.urls import url from . import views # This line is new! urlpatterns = [ url(r'^$', views.index) # This line has changed! ] # from django.conf.urls import url # # def index(request): # print "8" * 100 # print "8" * 100 # print "bannanapeel" # print "8" * 100 # print "8" * 100 # # urlpatterns = [ # url(r'^$', index) # ] # print " I will be your future routes; HTTP request will be captured by me" <file_sep>/Python/Learning_Python/Django_Projects/Courses_Project/apps/courses2/apps.py from __future__ import unicode_literals from django.apps import AppConfig class Courses2Config(AppConfig): name = 'courses2' <file_sep>/MEAN/basic_mongoose_app/routes/index.js 'use strict' //Our routes will go in this file this time around module.exports = function Route(app){ const mongoose = require('mongoose'); let UserSchema = new mongoose.Schema({ name: String, age: Number }) mongoose.model('User', UserSchema); // We are setting this Schema in our Models as 'User' let User = mongoose.model('User') // We are retrieving this Schema from our Models, named 'User' // Routes // Root Request app.get('/', function(req, res) { // This is where we will retrieve the users from the database and include them in the view page we will be rendering. User.find({},function(err,users_found) { if (err) { console.log("User was unable to be found"); }else { console.log("User successfully found"); res.render('index', {fetched_users: users_found}); //passing the users_found dictionary } }); }) // Add User Request app.post('/users', function(req, res) { console.log("POST DATA", req.body); // This is where we would add the user from req.body to the database. // create a new User with the name and age corresponding to those from req.body let users = new User({name: req.body.name, age: req.body.age}); //white matches the keys in the schema the last one(red) matches the html // Try to save that new user to the database (this is the method that actually inserts into the db) and run a callback function with an error (if any) from the operation. users.save(function(err,users) { // if there is an error console.log that something went wrong! if (err) { console.log("User was unable to be saved to the database"); }else { // else console.log that we did well and then redirect to the root route console.log("User successfully saved to database"); } }) res.redirect('/'); }) } <file_sep>/Python/Python_OOP_Cars.py class Car(object): def __init__(self, price,speed,fuel,mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage def display_all(self): if self.price > 10000: tax = .15 else: tax = .12 print self.price print self.speed print self.fuel print self.mileage print tax return Car1 = Car(9000,150,"Half Full",95) Car1.display_all() Car2 = Car(11000,160,"Full",100) Car2.display_all() Car3 = Car(2000,170,"Quarter Full",80) Car3.display_all() Car4 = Car(20000,120,"Full",125) Car4.display_all() Car5 = Car(5000,180,"Full",75) Car5.display_all() Car6 = Car(35000,190,"Completely Full",200) Car6.display_all() <file_sep>/WebFundamentals/Javascript/ContactCard/ContactCard_2_documentOn.js $("#contactAlt").hide(); $(document).on("click", "#adduser", function() { var FirstName = $("#FirstName").val(); var LastName = $("#LastName").val(); $(".contactCard").html("<p>"+FirstName+" "+LastName+"</p><p id =description>Click for Description</p>"); $("#description").click(function functionName() { var descript = $("#textbox").val(); $("#contactCard").hide(); $("#contactAlt").show(); $("#contactAlt").html("<p>"+descript+"</p>"); }); }); // console.log("hello"); // $("#contactCard").click(function () { // console.log("testing"); // $(".contactCard").html("<p>Test</p>"); // }); <file_sep>/MEAN/mongoose_dashboard/mongooseDashBoard.js 'use strict' //This file serves as our web server and our logic units // Require the Express Module const express = require('express'); // Require body-parser (to receive post data from clients) const bodyParser = require('body-parser'); // Require path const path = require('path'); const mongoose = require('mongoose'); // Create an Express App let app = express(); // Integrate body-parser with our App app.use(bodyParser.urlencoded({ extended: true })); // Setting our Static Folder Directory app.use(express.static(path.join(__dirname, './static'))); // Setting our Views Folder Directory app.set('views', path.join(__dirname, './views')); // Setting our View Engine set to EJS app.set('view engine', 'ejs'); // This is how we connect to the mongodb database using mongoose -- "basic_mongoose" is the name of // our db in mongodb -- this should match the name of the db you are going to use for your project. mongoose.connect('mongodb://localhost/animal_dashboard'); // Setting our Server to Listen on Port: 8000 //This next line allows us to organize our code a bit better //Here we pass our express app instance to our index.js file in route folder let route = require('./routes/index.js')(app);//Immediatly envoke the function with our app as a param app.listen(8000, function() { console.log("listening on port 8000"); }) <file_sep>/MEAN/ANGULAR/learning_angular/angular_controller.js var app = angular.module('app', []); app.controller('myController', ['$scope', function($scope){ //printController will show the current $scope $scope.foodlist = [ ]; $scope.addFood = function (){ // add to the array $scope.foodlist.push($scope.newFood); // clear the form values $scope.newFood = ""; } }]); <file_sep>/MEAN/ANGULAR/try_two/client/assets/factories/questionFactory.js app.factory('questionFactory', ['$http', function($http) { function QuestionFactory() { let _this = this; this.addQuestion = function(question, callback) { $http.post("/questions", question).then(function(returnedData) { callback(returnedData.data); }); }; this.getQuestions = function(callback) { $http.get('/questions').then(function(returnedData) { callback(returnedData.data); }); }; this.getCurrentQuestion = function(id, callback) { $http.get("/questions/" + id.id).then(function(returnedData){ callback(returnedData.data); }); }; } return new QuestionFactory(); }]); <file_sep>/Python/Learning_Python/Django_Projects/Courses_Project/apps/courses2/views.py from django.shortcuts import render, redirect from .models import Course def index(request): return render(request, "courses2/index.html") def destroy(request): return render(request, "courses2/destroy.html") <file_sep>/MEAN/ANGULAR/test_one/client/js/controller/login_controller.js app.controller('loginController', ["$scope","questionFactory","$location", function ($scope, questionFactory, $location) { $scope.user = {}; $scope.login = function () { if (!$scope.user.name) { console.log("Error"); alert("Name cannot be blank"); }else { questionFactory.login($scope.user, function(returnedData) { $location.url("/dashboard"); //This takes you to the dashboard after a succful login }) } } }]); <file_sep>/MEAN/node_server/app.js 'use strict' //getting the http module: let http = require('http'); //This lets us utilize the fs module to read and write content for responses let fs = require('fs'); //THIS LINE IS IMPORTANT // This line lets us use the http module to create a server let server = http.createServer(function (request, response){ //This allows us to see what URL the clients are requesting: console.log('client request URL:', request.url); //OUR ROUTES GO HERE //------------------------------------------------------------------------------- if(request.url === '/'){ fs.readFile('index.html', 'utf8', function (errors, contents){ response.writeHead(200, {'Content-Type': 'text/html'}); //send data about response response.write(contents); //send response body response.end(); //finished! }); }else if (request.url === "/ninjas") { fs.readFile('ninjas.html', 'utf8', function (errors, contents){ response.writeHead(200, {'Content-Type': 'text/html'}); //send data about response response.write(contents); //send response body response.end(); //finished! }); }else if (request.url === "/dojos/new") { fs.readFile('dojos.html', 'utf8', function (errors, contents){ response.writeHead(200, {'Content-Type': 'text/html'}); //send data about response response.write(contents); //send response body response.end(); //finished! }); } else { response.writeHead(404); response.end('File not found!!!'); } }); // => functionName() { // // } //------------------------------------------------------------------------------- //This line tells the server which port to run on server.listen(6789); //Print this to our terminal window console.log("Running in localhost at port 6789"); <file_sep>/WebFundamentals/Javascript/While you wait.js /* Using a while loop... While You Wait Create a birthday countdown. var daysUntilMyBirthday = 60; Copy For every day, print how many days left. If it's more than 30 days, print a sad message. If it's less than 30 days, print a message sound excited! If it's less than 5 days, SCREAM IT! ONCE IT'S YOUR BIRTHDAY HAVE PARTY! 60 days until my birthday. Such a long time... :( 59 days until my birthday. Such a long time... :( 58 days until my birthday. Such a long time... :( 2 DAYS UNTIL MY BIRTHDAY!!! 1 DAY UNTIL MY BIRTHDAY!!! ♪ღ♪*•.¸¸¸.•*¨¨*•.¸¸¸.•*•♪ღ♪¸.•*¨¨*•.¸¸¸.•*•♪ღ♪•* ♪ღ♪░H░A░P░P░Y░ B░I░R░T░H░D░A░Y░░♪ღ♪ *•♪ღ♪*•.¸¸¸.•*¨¨*•.¸¸¸.•*•♪¸.•*¨¨*•.¸¸¸.•*•♪ღ♪•« */ var daysUntilMyBirthday = 60; while(daysUntilMyBirthday > 0){ if (daysUntilMyBirthday >= 30) { console.log("Such a long time"); }else if (daysUntilMyBirthday > 5 && daysUntilMyBirthday <= 29 ) { console.log("getting closer"); }else if (daysUntilMyBirthday <= 5) { console.log("SO CLOSE!!!"); } daysUntilMyBirthday--; } console.log("ITS YOUR BIRTHDAY!!!"); console.log("♪ღ♪*•.¸¸¸.•*¨¨*•.¸¸¸.•*•♪ღ♪¸.•*¨¨*•.¸¸¸.•*•♪ღ♪•* \n♪ღ♪░H░A░P░P░Y░ B░I░R░T░H░D░A░Y░░♪ღ♪ \n*•♪ღ♪*•.¸¸¸.•*¨¨*•.¸¸¸.•*•♪¸.•*¨¨*•.¸¸¸.•*•♪ღ♪•«"); <file_sep>/Python/String and List Pratice.py import re mystr = "If monkeys like bananas, then I must be a monkey!" # generalized version using regular expressions for cases where there are more than 2 substrings for sub in re.finditer("monkey", mystr): print("monkey found", sub.start(), sub.end()) #range of substring print mystr.find("monkey") print mystr.rfind("monkey") print mystr.replace("monkey", "alligator") x = [2,54,-2,7,12,98] print min(x), max(x) y = ["hello",2,54,-2,7,12,98,"world"] print y[0], y[len(y)-1] newlist = [y[0], y[len(y)-1]] print newlist z = [19,2,54,-2,7,12,98,32,10,-3,6] z.sort() print z new_z = z[0:2] z.remove(-3) z.remove(-2) print new_z z.insert(0, new_z) print z <file_sep>/MEAN/survey_form/survey.js 'use strict' //allows our app to untilize the express module const express = require("express"); //This preps our server to use the body-parser module const bodyParser = require("body-parser"); //allows our app to untilize the session module const session = require('express-session'); //allows our app to untilize the path module const path = require("path"); //This comes with node by default let app = express(); app.use(bodyParser.urlencoded({extended: true})); //This allows us to actually use body-parser //This is for our static content app.use(express.static(path.join(__dirname, "./static"))); //The "path.join" part is new here app.set('views', path.join(__dirname, './views')); app.set('view engine', 'ejs'); //ejs stands for embedded javascript app.use(session({secret: 'THIS IS DISCRETE!!!'})); //we use session here to toss around information //This next line allows us to organize our code a bit better //Here we pass our express app instance to our index.js file in route folder let route = require('./routes/index.js')(app);//Immediatly envoke the function with our app as a param //Finally we tell our express app ot run on a specified port app.listen(8000, function(){ console.log("Listening on port 8000"); }); <file_sep>/WebFundamentals/Javascript/Fancy Array.js /* Fancy Array Normally, if you print an array such as ["James", "Jill", "Jane", "Jack"], you will see the following: [ "James", "Jill", "Jane", "Jack" ] Let's make it look fancy! Write a function that will make it print like: 0 -> James 1 -> Jill 2 -> Jane 3 -> Jack Bonus (Only If You Have Time): Let the user pass in the symbol that will print (ex: "->", "=>", "::", "-----") Have an extra parameter reversed. If the user passes true, print the elements in reverse order */ // var arr = [2,4,6,8,777]; // var last = arr.pop(); /// pop() grabs AND returns the last value of the array // console.log(last); var arrNames = [ "James", "Jill", "Jane", "Jack" ]; function fancyArray(arr,sym,reversed = false) { //ignore this if (reversed === true) { for (var j = arr.length - 1; j >= 0; j--) { console.log(j + sym + arr[j]); } }else { for (var i = 0; i < arr.length; i++) { console.log(i + sym + arr[i]); } } } fancyArray(arrNames,"->",false); fancyArray(arrNames,"->",true); <file_sep>/Python/Learning_Python/Django_Projects/login_Reg/apps/logNReg/models.py from __future__ import unicode_literals from django.db import models import re import bcrypt from django.contrib import messages EMAIL_REGXE = re.compile('^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') NAME_RE = re.compile(r'[a-zA-Z]{2,}') # Create your models here. class UserManager(models.Manager):# ORM def validateReg(self, *args): #first_name=0, last_name=1, email=2, password=3, confirm = 4 # def validateReg(self,email,first_name,last_name,password,request): if not NAME_RE.match(args[0]): return False elif not NAME_RE.match(args[1]): return False elif not EMAIL_REGXE.match(args[2]): return False elif len(args[3]) < 8: return False elif args[3] != args[4]: return False else: password = args[3].<PASSWORD>() pwhash = bcrypt.hashpw(password, bcrypt.gensalt()) super(UserManager, self).create(first_name=args[0], last_name = args[1],email=args[2],password=<PASSWORD>) return {'True': User.userManager.filter(email=args[2])[0].id} #returns a query set access first element in a list one one element # if len(last_name) > : # if len(password) > : def login(self, email, password):# orange is passed in email them = User.userManager.filter(email=email) #orange - database email, white is passed in email, them is set equal to the persons whole info set whos email equals the target email if not them: return False else: if not bcrypt.checkpw(password.encode(), them[0].password.encode): return False else: return {'True': them[0].id} #this is the user id class User(models.Model): first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) email = models.EmailField(max_length = 255) password = models.CharField(max_length = 255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) userManager = UserManager() #our defined instance of the UserManager class called userManager to extend the functionality of our Email class <file_sep>/Python/Names.py # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}, # {'first_name' : 'KB', 'last_name' : 'Tonel'} # ] # # print students[0] # # for i in range(len(students)): # print students[i]["first_name"] +" "+ students[i]["last_name"] # users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } print users["Students"][0]["first_name"] for i in range(len(users)/2): for j in range(len(users['Students'])): print str(j)+" "+users["Students"][j]["first_name"]+" "+users["Students"][j]["last_name"] +" "+ str((len(users["Students"][j]["first_name"])+len(users["Students"][j]["last_name"]))) for i in range(len(users)/2): for j in range(len(users['Instructors'])): print str(j)+" "+users["Instructors"][j]["first_name"]+" "+users["Instructors"][j]["last_name"] +" "+ str((len(users["Instructors"][j]["first_name"])+len(users["Instructors"][j]["last_name"]))) # Pair programmed with: <NAME>, <NAME>, <NAME>. <file_sep>/Python/Scores_and_Grades.py import random def scores_and_Grades(): for i in range(10): grade = random.randint(60,100) if grade >= 60 and grade<=69: print "Score: "+str(grade)+"; Your grade is a D" # return elif grade >= 70 and grade<=79: print "Score: "+str(grade)+"; Your grade is a C" # return elif grade >= 80 and grade<=89: print "Score: "+str(grade)+"; Your grade is a B" # return else: print "Score: "+str(grade)+"; Your grade is a A" return scores_and_Grades() <file_sep>/MEAN/ANGULAR/try_two/server/server_config/routes.js let users = require('../server_controllers/serv_users.js'); let questions = require('../server_controllers/serv_questions.js'); let answers = require('../server_controllers/serv_answers.js'); module.exports = function(app) { app.post("/login", users.login); app.get("/index", users.index); app.get("/logut", users.logout); // app.post("/questions", questions.create); // app.get("/questions", questions.index); }; <file_sep>/MEAN/message_board/server/config/mongoose_setup.js const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/message_board');//This is the line of code that actually lets us connect to our database // Use native promises mongoose.Promise = global.Promise; //We might not need this for this project let fs = require('fs'); //what is fs? let path = require('path'); let models_path = path.join(__dirname, '/../models'); fs.readdirSync(models_path).forEach(function (file) { if (file.indexOf('.js') > 0) { //Need to understand what this line of code is doing require(models_path + '/' + file); } }) <file_sep>/Python/Learning_Python/SQL/countries.sql SELECT languages.language, languages.percentage , countries.name FROM countries JOIN languages ON countries.id = languages.country_id WHERE languages.language = "Slovene" ORDER BY languages.percentage DESC; -- 8) -- SELECT countries.region, COUNT(countries.id) -- -- FROM -- -- GROUP by <file_sep>/Python/Coin Tosses.py import random heads = 0 tails = 0 for i in range(5001): tosses = random.randint(0,1) if tosses == 1: heads+=1 elif tosses ==0: tails+=1 print "Flipped a coin 5000 times and we got..." print str(heads) + " heads" print "and "+str(tails)+" tails" <file_sep>/MEAN/be_the_interpreter.js //NUMBER ONE--? Do we still need it to say undefined first? // console.log(first_variable); // var first_variable = "<NAME> was first!"; // function firstFunc() { // first_variable = "Not anymore!!!"; // console.log(first_variable); // } // console.log(first_variable); // // output: // undefined // Yipee I was first! //declarations get hoisted first in the order of variable then funciton // var first_variable; // function firstFunc() { // //then the things inside the funciton also get hoisted in the same order // first_variable = "Not anymore!!!"; // console.log(first_variable); // } // first_variable = "<NAME> was first!"; // console.log(first_variable); //---------------------------------------------------------- //NUMBER TWO // var food = "Chicken"; // function eat() { // food = "half-chicken"; // console.log(food); // var food = "gone"; // CAREFUL! // console.log(food); // } // eat(); // console.log(food); // // output: // half-chicken // gone // Chicken //Again declarations get hoisted first. First variable then funcitons // var food; // function eat(){ // var food; //Then follow the same logic for the function scope // food = "half-chicken"; // console.log(food); // food = "gone"; // console.log(food); // } // //Then the rest of the code follows // food = "Chicken"; // eat(); // console.log(food); // //-------------------------------------------------------- // //NUMBER THREE // var new_word = "NEW!"; // function lastFunc() { // new_word = "old"; // } // console.log(new_word); // // output: // // NEW! // var new_word; // function lastFunc(){ // new_word = "old"; // } // new_word = "NEW!"; // console.log(new_word); // //---------------------------------------------------------------- <file_sep>/MEAN/message_board/server/models/Post.js const mongoose = require('mongoose'); // define Schema variable let Schema = mongoose.Schema; // define Post Schema let PostSchema = new mongoose.Schema({ name: {type: String, required: true, min: [4, 'Name should be atleast 4 characters long'] }, message: {type: String, required: true }, _comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}] //underscore because this comes from another table }, {timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'} }); // just made the created_at and updated_at here Similar to python MySQL // set our models by passing them their respective Schemas mongoose.model('Post', PostSchema); // store our models in variables <file_sep>/MEAN/ANGULAR/product_factory/productFactory.js 'use strict' let myAppModule = angular.module('myApp', []); //factories are singletons //Instantiated once and then avaiable to the rest of the program myAppModule.factory('productFactory', ['$http', function($http) { let factory = {}; let products = []; //need to store products so that we can do operations on them //This is our index method that returns our products factory.index = function(callback){ //callback is the funciton that is passed to the productindex by the controller, in this caseP: setProducts callback(products); } //This is our add method factory.create = function(product, callback) { //how to we know price is an attribute of product? if(product.price && Number(parseFloat(product.price))==product.price){ product.qty = 50; //This works because whenever we want products.push(product); callback(products); } } factory.delete = function(id, callback){ products.splice(id,1); //this method of deletion assures us that we will be able to delete things at their specific index callback(products); } factory.buy = function(product, callback) { //what does this take? if (Number.isInteger(product.quantity)) { if (products[product.id].qty - product.qty > 0) { //pretty sure the first qty is the one above in this file and the second one is the one from the OrdersController file products[product.id].quantity -= product.quantity; }else { products[product.id].quantity = 0; } } callback(products); } //We return our object literal (let factory = {}) so that we may use it elsewhere throughout the program return factory; //So everything form myAppModule.factory to return factory is considered our factory generation function }]); <file_sep>/WebFundamentals/Javascript/If You Don't Mind.js /*Simply function to tell time Create a program that will tell you the time. With the following variables... var HOUR = 8; var MINUTE = 50; var PERIOD = "AM"; Copy ...your program should print "It's almost 9 in the morning" And when changed to... var HOUR = 7; var MINUTE = 15; var PERIOD = "PM"; Copy ...your program should print "It's just after 7 in the evening" Challenge: If minutes less than 30, "just after" the hour, more than 30, "almost" the next hour AM / PM, "in the morning", "in the evening", HINT You can add as many items into console.log as you need (They will be separated with spaces) Example: var person = "Jack"; var me = "Jill"; console.log("Hello", person, "I am", me, "."); // Hello Jack I am Jill. Copy Bonus (Only If You Have Time): Add functionality for "quarter after", "half past", "5 after" ... Distinguish between "in the afternoon", "at night", "noon", "midnight" ... */ /*STEPS -create function that takes in three arguments, HOUR, MINUTE, PERIOD -check the time see if within 10 mins of next hour if yes print "Its almost" + (HOUR+1) in the morning -check to see if minutes = 15 and check to see if PERIOD = am or pm if yes print "its just after" + HOUR + "in the" + PERIOD(am = morning/pm = evening) -check to see if minutes = >=30 if yes say "Soon it will be" + (HOUR + 1) "O'clock" if no but still greater than 15 "its almost,half past" + HOUR make similar things for 15 minutes and 5 minutes -check hour within a predefined time domain depending on the time augment the print stament to include "in the afternoon" / "at night", "noon", "midnight" moring = 12:01am to 11:59am noon = 12:00pm if(HOUR = 12 %% MINUTE = 0){} afternoon = 12:01 to 7:00pm nighttime = 7:01 to 11:59pm midnight = 12:00pm */ console.log("cat"); function timeOfDay(HOUR,MINUTE,PERIOD){ ///the following line breaks if you pass in 12 for the hour it gives back 13 (which isnt exactly wrong its just the only part of the porgram that would be using military time.) if((60 - MINUTE) <= 10 && PERIOD == "AM" || PERIOD == "am"){ ///there also might be a problem with this line regarding minutes being 0 console.log("Its almost " + (HOUR+1) + PERIOD,"in the morning"); }else if ((60 - MINUTE) <= 10 && PERIOD == "PM" || PERIOD == "pm" ) { console.log("Its almost " + (HOUR+1) + PERIOD); } ///check for part of day______________________________________________________ ///check for console.log("dog"); ///why does this print after bat? if (((HOUR >= 7 && HOUR <= 11) && (MINUTE > 0 && MINUTE <= 59) ) && PERIOD =="am" || PERIOD =="AM") { console.log("its currently morning"); }else if((HOUR === 12 && MINUTE === 0) && (PERIOD == "PM" || PERIOD == "pm") ){ console.log("its currently noon"); ///CHECK FOR NOON }else if ((HOUR === 12 && MINUTE === 0) && (PERIOD == "AM" || PERIOD == "am" )) { console.log("its currently midmignt"); ///CHECK FOR MIDNIGHT }else if (((HOUR >= 7 && HOUR <= 11) && (MINUTE > 0 && MINUTE <= 59) ) && PERIOD =="pm" || PERIOD =="PM"){ console.log("its nighttime"); } } console.log("bat"); timeOfDay(11,20,"pm"); <file_sep>/MEAN/js_fundamentals_three.js 'use strict' function personConstructor(param_name) { let person = { name: param_name, distance_traveled: 0, say_name: function () { console.log(person.name); return; // returns undefined }, say_something: function (param) { console.log(person.name + " says " + param); return; }, walk: function () { console.log(person.name + " is walking ") person.distance_traveled += 3; console.log(person.distance_traveled); }, run: function () { console.log(person.name + " is running ") person.distance_traveled += 10; console.log(person.distance_traveled); }, crawl: function () { console.log(person.name + " is crawling ") person.distance_traveled += 1; console.log(person.distance_traveled); }, }; // console.log("You made a person named "+ person.name+"!"); return person } // // personConstructor("Drake"); // console.log(personConstructor("Drake").name); // console.log(personConstructor("Drake").say_something("Hello world")); // console.log(personConstructor("Drake").walk()); function makeNinja(param_name, cohort) { let ninja = { name: param_name, cohort: cohort, // belt_level: belt, level_up: function (level) { let belt = "no belt"; if (level === 1) { belt = "Yellow"; }else if (level === 2) { belt = "Red" }else { belt = "Black"; } return belt; } , } return ninja; } console.log(makeNinja("Jon","MEAN").name); console.log(makeNinja("Jon","MEAN").cohort); console.log(makeNinja("Jon","MEAN").level_up(3));
a6955f9ba3f6cedc9ae0d1456a78b684b655a210
[ "SQL", "HTML", "JavaScript", "Markdown", "Python" ]
73
Python
Jonathan-Eboh/WebDevelopment
03c14195ec2c522e3bba6cb7d5d6bfa8cff8623f
f584c0ccb103aee1775a7d00094c5639f9f3499e
refs/heads/master
<repo_name>pigey/variabel-labbar<file_sep>/variabellabbar/src/main/java/se/filip/Lab5.java package se.filip; public class Lab5 { public void Execute(){ System.out.println("Mata in nummer 1: "); int num1 = Integer.parseInt(System.console().readLine()); System.out.println("Mata in nummer 2: "); int num2 = Integer.parseInt(System.console().readLine()); int result = num1 * num2; System.out.println(result); int pow = (int)Math.pow(num1 , num2); System.out.println(pow); float div = (float)num1 / (float)num2; System.out.println(div); System.out.println(num1 + num2); System.out.println(num1 - num2); } } <file_sep>/variabellabbar/src/main/java/se/filip/Lab2.java package se.filip; public class Lab2 { public void Execute(){ String name = "Filip"; int age = 21; System.out.println("jag heter "+ name +" och är " + age + " år gammal"); } }
0aa7263ccc9969141c9d0e7502e9e256c18d1ac0
[ "Java" ]
2
Java
pigey/variabel-labbar
9552a61613cb4b0ad412fff4f4bfe65c967e866d
b448edd62fcf0f6828dea1441dc49c10e9cb32fc
refs/heads/master
<file_sep>// // CalendarViewController.swift // TestApp1 // // Created by <NAME> on 7/8/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CalendarViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } <file_sep># MoveTheEarthApp Powerlifting &amp; health-based iOS App. Report is linked here: https://docs.google.com/document/d/1pYLFrX4qAp_fLJdlanWYrLAlOdWDGDz_FReZX_Z_H0Q/edit?usp=sharing <file_sep>// // ViewController.swift // TestApp1 // // Created by <NAME> on 6/18/20. // Copyright © 2020 <NAME>. All rights reserved. // import FSCalendar import UIKit class ViewController: UIViewController, FSCalendarDelegate { @IBOutlet var calendar: FSCalendar! override func viewDidLoad() { super.viewDidLoad() } @IBAction func didTapButton() { guard let vc = storyboard?.instantiateViewController(identifier: "calendar_vc") as? CalendarViewController else { return } present(vc, animated: true) } }
89dd91a874803e969ce435581da0e3614383d052
[ "Swift", "Markdown" ]
3
Swift
jjtrinh99/TestApp1MTE
e42afe3d15b3099004422d16b204ee77dc6d8f32
045699f123653c32cd795917bfeee30cdec51789
refs/heads/master
<repo_name>QMSS-G5072-2020/final_project_zhang_alysandra<file_sep>/smithsonian_queri/smithsonian_queri.py import requests import json import csv import time def create_smithsonian_csv(category, api_key): """ Query data from the Smithsonian Open Access API using category filters provided by user input. Parameters ---------- Enter string input. create_smithsonian_csv("userinput", "apikey") Returns ------- userinput_smithsonian_data.csv Function will return a .csv file with Smithsonian data that matches the specified search parameter. Examples -------- >>> from smithsonian_queri import smithsonian_queri >>> smithsonian_queri.create_smithsonian_csv("postmodernism", "apikey") 200 Querying database... Querying database... Querying database... Querying database... Querying database... Querying database... Querying database... Querying database... Querying database... Querying database... File finished. """ assert isinstance(category, str), "Search query must be entered as a string." base = "https://api.si.edu/openaccess/api/v1.0/search?" start = "start=1&" size_of_array = 1000 row = "rows=" + str(size_of_array) + "&" api_url = base + start + row + "q=" + category + "&api_key=" + api_key print(api_url) api_response = requests.get(api_url) smithsonian_metadata = json.loads(api_response.text) print(api_response.status_code) with open("%s_smithsonian_data.csv" % category, "w") as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(["id", "title", "object_type", "physicalDescription", "date", "data_source", "record_link"]) for line in range(1, 10000, size_of_array): time.sleep(5) start = f"start={line}" + "&" api_url = base + start + row + "q=" + category + "&api_key=" + api_key api_response = requests.get(api_url) smithsonian_metadata = json.loads(api_response.text) print("Querying database...") if smithsonian_metadata["response"].get("rows") is not None: for artwork in smithsonian_metadata["response"]["rows"]: physical_description = artwork["content"]["freetext"].get("physicalDescription", None) smithsonian_data_row = [ artwork.get("id", None), artwork.get("title", None), ", ".join(artwork["content"]["indexedStructured"].get("object_type", [])), physical_description[0].get("content") if physical_description is not None else "", ", ".join(artwork["content"]["indexedStructured"].get("date", [])), artwork["content"]["descriptiveNonRepeating"].get("data_source", []), artwork["content"]["descriptiveNonRepeating"].get("record_link", None) ] csv_writer.writerow(smithsonian_data_row) print("File finished.") <file_sep>/docs/_build/html/_sources/source/smithsonian_queri.rst.txt smithsonian\_queri package ========================== Submodules ---------- smithsonian\_queri.smithsonian\_queri module -------------------------------------------- .. automodule:: smithsonian_queri.smithsonian_queri :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: smithsonian_queri :members: :undoc-members: :show-inheritance: <file_sep>/docs/usage.rst ===== Usage ===== To use smithsonian_queri in a project:: import smithsonian_queri <file_sep>/README.md # smithsonian_queri ![](https://github.com/Alys-217/smithsonian_queri/workflows/build/badge.svg) [![codecov](https://codecov.io/gh/Alys-217/smithsonian_queri/branch/main/graph/badge.svg)](https://codecov.io/gh/Alys-217/smithsonian_queri) ![Release](https://github.com/Alys-217/smithsonian_queri/workflows/Release/badge.svg) [![Documentation Status](https://readthedocs.org/projects/smithsonian_queri/badge/?version=latest)](https://smithsonian_queri.readthedocs.io/en/latest/?badge=latest) Python package designed to query data from the Smithsonian Open Access API using category filters based on user input. ## Installation ```bash $ pip install smithsonian_queri ``` ## Features - Query data from the Smithsonian Open Access API using specified search parameters based on user input - Generate spreadsheet (.csv) with public domain metadata on objects (e.g., artwork, exhibitions, books, documentaries, etc.) within the Smithsonian Institution's collections ## Dependencies - pandas ## Usage and Documentation The official documentation is hosted on Read the Docs: https://smithsonian_queri.readthedocs.io/en/latest/ ## Contributors We welcome and recognize all contributions. You can see a list of current contributors in the [contributors tab](https://github.com/Alys-217/smithsonian_queri/graphs/contributors). ### Credits This package was created with Cookiecutter and the UBC-MDS/cookiecutter-ubc-mds project template, modified from the [pyOpenSci/cookiecutter-pyopensci](https://github.com/pyOpenSci/cookiecutter-pyopensci) project template and the [audreyr/cookiecutter-pypackage](https://github.com/audreyr/cookiecutter-pypackage). <file_sep>/pyproject.toml [tool.poetry] name = "smithsonian_queri" version = "0.1.0" description = "Python package designed to query data from the Smithsonian Open Access API using category filters based on user input." authors = ["Alys-217 <<EMAIL>>"] license = "MIT" [tool.poetry.dependencies] python = "^3.8" pandas = "^1.1.5" [tool.poetry.dev-dependencies] sphinx = "^3.3.1" sphinxcontrib-napoleon = "^0.7" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" <file_sep>/tests/test_smithsonian_queri.py from smithsonian_queri import __version__ from smithsonian_queri import smithsonian_queri def test_version(): assert __version__ == '0.1.0'
c0f0e4b148af0291e3986f794c12e25a93dcef39
[ "Markdown", "TOML", "Python", "reStructuredText" ]
6
Python
QMSS-G5072-2020/final_project_zhang_alysandra
591bb68442c231f972fc0e83a26360e643d1a3ca
55138af8d7eb769b78a3c1bf04f17a55d6317293
refs/heads/main
<file_sep> -- deletes the entire table -- DROP TABLE Students; -- CREATE TABLE students( -- id INTEGER PRIMARY KEY, -- firstName VARCHAR(100), -- lastName VARCHAR(100), -- age INTEGER -- ); -- ALTER TABLE students ADD email VARCHAR(100); -- this creates a table -- CREATE TABLE courses ( -- id INTEGER PRIMARY KEY, -- title VARCHAR(250) -- ); -- this represents through / join table -- FOREIGN KEY (an attribute in the current table thta references the primary key of another table) REFERENCES targetTable(target colum with primary key) /* CREATE TABLE enrollment ( id INTEGER PRIMARY KEY, courseId INTEGER, studentId INTEGER, FOREIGN KEY (courseId) REFERENCES courses(id), FOREIGN KEY (studentId) REFERENCES students(id) ); */ -- inserting data into a table /* INSERT INTO students VALUES (1, "Joshua", "Roth", 27, "<EMAIL>"), (2, "Brandon", "Roth" , 26, "<EMAIL>"), (3, "Drake", "Scott", 35, "<EMAIL>"); INSERT INTO courses VALUES (1, "English"), (2, "Math"), (3, "Science"), (4, "Java"); */ /* INSERT INTO enrollment VALUES (1, 2, 1), (2, 3, 3), (3, 2, 1), (4, 4, 3), (5, 4, 2), (6, 1, 2); */ -- to get all the data on a table SELECT * FROM students; SELECT firstName, lastName FROM students; SELECT firstName, lastName FROM students LIMIT 2; SELECT firstName, lastName FROM students WHERE age < 25; SELECT firstName, lastName FROM students ORDER BY firstName; Select firstName, lastName FROM students ORDER BY firstName DESC; -- order in the inverse alphabet
6e136d14a7467e7f65ba0862138843826fb2fbbf
[ "SQL" ]
1
SQL
JoshRoth909/myFirstSQL
44b1bc6f4b239bfe747fe8b60d1051c93844167e
c4c65400d6b5fb9fed0a49f8041009609df358af
refs/heads/main
<file_sep>// // Model.swift // middle_todo // // Created by suhee❤️ on 2021/07/14. // import Foundation //class Memo { // var content: String // var insertDate: Date // init(content: String) { // self.content = content // insertDate = Date() // } // // static var dummnyMemoList = [ // Memo(content: "Create by middle Team."), // Memo(content: "Hello, Middle peoples.") // ] //} <file_sep># middle_ios IOS App initialized
38e51ac4f637cc7556f0fea304edad4d4850dbb8
[ "Swift", "Markdown" ]
2
Swift
comeevery-git/middle_ios
00417ddf4000192045adbf4548ac4ae701613499
e0b8f00f3787f92c779b73edec7ea60148f54a03
refs/heads/master
<repo_name>linylmfos/react_demo<file_sep>/src/StateCom.js import React, { Component } from 'react'; class Cmp1 extends React.Component{ constructor(props) { super(props); this.state = { a: 4 } console.log('a', this.state.a); } fn() { this.setState({ a: this.state.a + 1 }); console.log('aa', this.state.a); } render() { return ( <div> {this.state.a} <input type="button" value="+1" onClick={this.fn.bind(this)} /> </div> ) } } export default Cmp1;<file_sep>/src/WillUnmount.js import React, { Component } from 'react'; class Parent extends React.Component{ constructor(props) { super(props); this.state = { b: true } } fn() { this.setState({ b: !this.state.b }); } render() { return ( <div> <input typed="button" value="Be/Not to Be" onClick={this.fn.bind(this)} /> {this.state.b ? <Child /> : ('') } </div> ) } } class Child extends React.Component { constructor(props) { super(props); } componentDidMount() { console.log('mount'); } componentWillUnmount() { console.log('unmount'); } render() { return ( <p>隔壁王</p> ) } } export default Parent;<file_sep>/src/Trans.js import React, { Component } from 'react'; class Parent extends React.Component{ constructor(props) { super(props); this.state = { aValue: 50 }; } fn2(aValue) { console.log('trigged', aValue); this.state.aValue = aValue; } render() { return ( <div> <Child myFunc={this.fn2.bind(this)} /> </div> ) } } class Child extends React.Component { constructor(props) { super(props); this.state = { myValue : 25 } } fn() { this.props.myFunc(this.state.myValue) } render() { return ( <div> <input type="button" value="send" onClick={this.fn.bind(this)} /> </div> ) } } export default Parent;<file_sep>/src/ShouldCom.js import React, { Component } from 'react'; import Axios from 'axios'; class Parent extends React.Component { constructor(props) { super(props); this.state = { id: 1 } } next() { if (this.state.id < 3) { this.setState({ id: this.state.id + 1 }) } else { this.setState({ id: 1 }) } } render() { return ( <div> <input type="button" value="next" onClick={this.next.bind(this)} /> <Child id={this.state.id} /> </div> ) } } class Child extends React.Component { constructor(props) { super(props); this.state = { name: '', age: '' } } shouldComponentUpdate(nextProps, nextState) { console.log(nextProps, nextState); return ( nextProps.id !== this.props.id || nextState.name !== this.state.name ) // return true } loadData(id) { console.log('id',id); fetch(`data/data${id}.json`, { headers: { 'content-type': 'application/json' } }).then(res => { res.json().then(data => { console.log('d', data) this.setState(data); }).catch(err => { }).finally(() => { var data; if(id === 1) { data = { "name": "张三", "age": 18 } this.setState(data); } else if(id ===2){ data = { "name": "张三丰", "age": "20" } this.setState(data); } else if(id === 3) { data = { "name": "张丰", "age": "22" } this.setState(data); } }) }) } componentDidMount() { console.log('Mount', this.props.id); this.loadData(this.props.id); } componentDidUpdate() { console.log('update', this.props.id); this.loadData(this.props.id); } render() { return ( <div> <h2>ID: {this.props.id}</h2> <p>用户名: {this.state.name}<br/> 年龄: {this.state.age}</p> </div> ) } } export default Parent<file_sep>/src/Life.js import React, { Component } from 'react'; class Cmp11 extends React.Component{ constructor(props) { super(props); console.log('calling constructor'); this.state = { a: 5 }; } fn() { this.setState({ a: this.state.a + 1 }) } shouldComponentUpdate(nextProps, nextState) { console.log('nextProps', nextProps); console.log('nextState', nextState); console.log('this.state', this.state); console.log('this.props', this.props); if(nextState.a % 2 === 1) { return true } else { return false; } } componentWillMount() { console.log('will mount'); } componentDidMount() { console.log('did mount'); } componentWillUpdate() { console.log('will update'); } componentDidUpdate() { console.log('did update') } render() { return ( <div> a = {this.state.a} <input type="button" value="+1" onClick={this.fn.bind(this)} /> </div> ) } } export default Cmp11; <file_sep>/src/ForceUpdate.js import React, { Component, useDebugValue } from 'react'; class Cmp1 extends React.Component { constructor(props) { super(props); this.a = 5; console.log('a', this.a); } fn() { this.a++; console.log(this.a); this.forceUpdate(); } render() { console.log('渲染啦'); return ( <div> {this.a} <input type="button" value="+1" onClick={this.fn.bind(this)} /> </div> ) } } export default Cmp1; <file_sep>/src/App.js import React from 'react'; import MyComponent from './MyCom' import StateCom from './StateCom' import StateCom2 from './StateCom2' import PropsRender from './PropsRender'; import ForceUpdate from './ForceUpdate'; import Life from './Life' import ShouldCom from './ShouldCom' import WillUnmount from './WillUnmount'; import Trans from './Trans' import Refer from './Refer' import RefComm from './RefComm' import './App.css'; function App() { let array1 = [1, 2, 3, 4, 5]; let users = [ {id: 's01', name: '张三', age: 25}, {id: 's02', name: '张四', age: 26}, {id: 's03', name: '万股', age: 27}, ] // let array2 = array1.filter(isLarger); let name = "老王"; let age = 22; let childrenStr = [ { id: 's01', str: '隔壁老王1' }, { id: 's02', str: '隔壁老王2' }, { id: 's03', str: '隔壁老王3' } ] let children = childrenStr.map((item, index) => ( <h4 key={item.id}>{item.str}</h4> )); let mcpt = <MyComponent name={name} age={age} /> let obj = { a: 5 } return ( <div> <div className="App"> <h1> <RefComm /> <hr /> </h1> <h1> <Refer /> </h1> <p> <Trans /> </p> <p> <WillUnmount /> </p> <ul> { users.map((item, index) => ( <Child key={item.id} name={item.name} age={item.age} /> )) } </ul> </div> <div> <ShouldCom /> </div> <h4> <hr /> <StateCom /> <hr /> </h4> <p> <PropsRender /> </p> <h6 style={{color: 'green', backgroundColor: '#F00'}}> <ForceUpdate a={5} /> </h6> <p style={{background: '#FF0'}}> <Life /> </p> <p> <StateCom2 a={5} obj={obj} > <span id="ss1">aaa</span> <span id="ss2">bbb</span> </StateCom2> <hr /> </p> <div> {children} </div> {mcpt} </div> ); } class Child extends React.Component { constructor(props) { super(props); } render() { return ( <li style={{color:'red'}}> name: {this.props.name} age: {this.props.age} </li> ) } } export default App;
32c69d2a175d24b12f8f001387b25852b618d349
[ "JavaScript" ]
7
JavaScript
linylmfos/react_demo
52e364047fa8df8c035e3b749b35d5a070f9fbe6
4f704c11bb0b5eacc17d3a4c5a9d9411fcdf006c
refs/heads/master
<file_sep>import * as fs from 'fs' import { featureCollection, polygon } from '@turf/helpers' import geobuf from 'geobuf' import * as jsts from 'jsts' import _ from 'lodash' import Pbf from 'pbf' const geoJsonReader = new jsts.io.GeoJSONReader() const geoJsonWriter = new jsts.io.GeoJSONWriter() export default function (tzGeojson, dataDir, targetIndexPercent, callback) { console.log('indexing') const data = { timezones: [], lookup: {}, } /** * iterate through geometry coordinates and change any coordinates along * longitude 0 to longitude 0.00001 */ function hackLongitude0Polygon(polygon) { polygon.forEach((linearRing) => { linearRing.forEach((ringCoords) => { if (ringCoords[0] === 0 && ringCoords[1] < -55) { ringCoords[0] = 0.00001 } }) }) } const timezoneGeometries = tzGeojson.features.map((feature) => { // Perform a quick hack to make sure two Antarctic zones can be indexed // properly. Each of these zones shares a boundary at longitude 0. During // the quadtree analysis, the zones were being intersected right aloing // their boundaries which resulted in LineStrings being returned. This hack // changes their boundares along longitude 0 to longitude 0.00001 to avoid // LineStrings being intersected. if ( feature.properties.tzid === 'Africa/Johannesburg' || feature.properties.tzid === 'Antarctica/Troll' ) { if (feature.geometry.type === 'MultiPolygon') { feature.geometry.coordinates.forEach(hackLongitude0Polygon) } else { hackLongitude0Polygon(feature.geometry.coordinates) } } // load zone into memory as jsts geometry return geoJsonReader.read(JSON.stringify(feature.geometry)) }) let debugWriteIdx = 1 const writeDebugData = function (filename, geom) { fs.writeFileSync( 'debug_' + debugWriteIdx + '_' + filename + '.json', JSON.stringify(geoJsonWriter.write(geom)) ) } const getIntersectingGeojson = function (tzIdx, curBoundsGeometry) { // console.log('intersecting', tzGeojson.features[tzIdx].properties) const intersectedGeometry = timezoneGeometries[tzIdx].intersection(curBoundsGeometry) const intersectedGeoJson: any = geoJsonWriter.write(intersectedGeometry) if ( intersectedGeoJson.type === 'GeometryCollection' && intersectedGeoJson.geometries.length === 0 ) { return undefined } else { const tzName = data.timezones[tzIdx] // If the geojson type is not a Polygon or a MultiPolygon, something weird // is happening and the build should be failed as this will cause issues // during the find method. // See https://github.com/evansiroky/node-geo-tz/issues/90. if (!intersectedGeoJson.type.match(/olyg/)) { console.log(tzName) console.log(intersectedGeoJson.type) writeDebugData('tz', timezoneGeometries[tzIdx]) writeDebugData('curBounds', curBoundsGeometry) writeDebugData('intersection', intersectedGeometry) debugWriteIdx++ } return { type: 'Feature', properties: { tzid: null, }, geometry: intersectedGeoJson, } } } /** * Check if certain timezones fall within a specified bounds geometry. * Also, check if an exact match is found (ie, the bounds are fully contained * within a particular zone). * * @param {Array<number>} timezonesToInspect An array of indexes referencing * a particular timezone as noted in the tzGeojson.features array. * @param {Geometry} curBoundsGeometry The geometry to check */ const inspectZones = function (timezonesToInspect, curBoundsGeometry) { const intersectedZones = [] let numberOfZonesThatContainBounds = 0 for (let j = timezonesToInspect.length - 1; j >= 0; j--) { const curZoneIdx = timezonesToInspect[j] const curZoneGeometry = timezoneGeometries[curZoneIdx] if (curZoneGeometry.intersects(curBoundsGeometry)) { // bounds and timezone intersect, add to intersected zones intersectedZones.push(curZoneIdx) // check if tz fully contains bounds if (curZoneGeometry.contains(curBoundsGeometry)) { // bounds fully within tz numberOfZonesThatContainBounds += 1 } } } return { intersectedZones, numberOfZonesThatContainBounds, } } let filePosition = 0 // analyze each unindexable area in a queue, otherwise the program may run out // of memory function writeUnindexableData(unindexableData, geoDatFd) { const features = [] // calculate intersected area for each intersected zone for (let j = unindexableData.intersectedZones.length - 1; j >= 0; j--) { const tzIdx = unindexableData.intersectedZones[j] const intersectedGeoJson = getIntersectingGeojson( tzIdx, unindexableData.curBoundsGeometry ) if (intersectedGeoJson) { intersectedGeoJson.properties.tzid = data.timezones[tzIdx] features.push(intersectedGeoJson) } } const areaGeoJson: any = featureCollection(features) const buf = Buffer.from(geobuf.encode(areaGeoJson, new Pbf())) fs.writeSync(geoDatFd, buf, 0, buf.length) const ret = { pos: filePosition, len: buf.length, } filePosition += buf.length return ret } // create array and index lookup of timezone names for (let i = 0; i < tzGeojson.features.length; i++) { data.timezones.push(tzGeojson.features[i].properties.tzid) } // recursively generate index until 99% of planet is indexed exactly let curPctIndexed = 0 let curLevel = 1 let expectedAtLevel = 4 let curZones = [ { id: 'a', bounds: [0, 0, 179.9999, 89.9999], }, { id: 'b', bounds: [-179.9999, 0, 0, 89.9999], }, { id: 'c', bounds: [-179.9999, -89.9999, 0, 0], }, { id: 'd', bounds: [0, -89.9999, 179.9999, 0], }, ] let printMod, curZone, curBounds, curBoundsGeometry while (curPctIndexed < targetIndexPercent) { const nextZones = [] console.log('*********************************************') console.log('level', curLevel, ' pct Indexed: ', curPctIndexed) console.log('*********************************************') printMod = Math.round(curZones.length / 5) for (let i = curZones.length - 1; i >= 0; i--) { if (i % printMod === 0) { console.log( 'inspecting index area ', curZones.length - i, ' of ', curZones.length ) } curZone = curZones[i] curBounds = curZone.bounds curBoundsGeometry = geoJsonReader.read( JSON.stringify( polygon([ [ [curBounds[0], curBounds[1]], [curBounds[0], curBounds[3]], [curBounds[2], curBounds[3]], [curBounds[2], curBounds[1]], [curBounds[0], curBounds[1]], ], ]).geometry ) ) // calculate intersection with timezone boundaries let timezonesToInspect = [] if (curZone.tzs) { // only examine confirmed timezones found in last iteration timezonesToInspect = curZone.tzs } else { // first iteration, find all intersections in world for (let j = tzGeojson.features.length - 1; j >= 0; j--) { timezonesToInspect.push(j) } } const result = inspectZones(timezonesToInspect, curBoundsGeometry) const intersectedZones = result.intersectedZones const numberOfZonesThatContainBounds = result.numberOfZonesThatContainBounds let zoneResult: any = -1 // defaults to no zones found // check the results if ( intersectedZones.length === numberOfZonesThatContainBounds && numberOfZonesThatContainBounds > 0 ) { // analysis zones can fit completely within current quad zoneResult = intersectedZones } else if (intersectedZones.length > 0) { // further analysis needed const topRight = { id: curZone.id + '.a', tzs: intersectedZones, bounds: [ (curBounds[0] + curBounds[2]) / 2, (curBounds[1] + curBounds[3]) / 2, curBounds[2], curBounds[3], ], } const topLeft = { id: curZone.id + '.b', tzs: intersectedZones, bounds: [ curBounds[0], (curBounds[1] + curBounds[3]) / 2, (curBounds[0] + curBounds[2]) / 2, curBounds[3], ], } const bottomLeft = { id: curZone.id + '.c', tzs: intersectedZones, bounds: [ curBounds[0], curBounds[1], (curBounds[0] + curBounds[2]) / 2, (curBounds[1] + curBounds[3]) / 2, ], } const bottomRight = { id: curZone.id + '.d', tzs: intersectedZones, bounds: [ (curBounds[0] + curBounds[2]) / 2, curBounds[1], curBounds[2], (curBounds[1] + curBounds[3]) / 2, ], } nextZones.push(topRight) nextZones.push(topLeft) nextZones.push(bottomLeft) nextZones.push(bottomRight) zoneResult = { a: intersectedZones, b: intersectedZones, c: intersectedZones, d: intersectedZones, } } if (zoneResult !== -1) { _.set(data.lookup, curZone.id, zoneResult) } else { _.unset(data.lookup, curZone.id) } } // recalculate pct indexed after this round expectedAtLevel = Math.pow(4, curLevel + 1) curPctIndexed = (expectedAtLevel - nextZones.length) / expectedAtLevel curZones = nextZones curLevel++ } console.log('*********************************************') console.log('reached target index: ', curPctIndexed) console.log('writing unindexable zone data') const geoDatFd = fs.openSync(`${dataDir}/geo.dat`, 'w') printMod = Math.round(curZones.length / 5) // process remaining zones and write out individual geojson for each small region for (let i = curZones.length - 1; i >= 0; i--) { if (i % printMod === 0) { console.log( 'inspecting unindexable area ', curZones.length - i, ' of ', curZones.length ) } curZone = curZones[i] curBounds = curZone.bounds curBoundsGeometry = geoJsonReader.read( JSON.stringify( polygon([ [ [curBounds[0], curBounds[1]], [curBounds[0], curBounds[3]], [curBounds[2], curBounds[3]], [curBounds[2], curBounds[1]], [curBounds[0], curBounds[1]], ], ]).geometry ) ) // console.log('writing zone data `', curZone.id, '`', i ,'of', curZones.length) const result = inspectZones(curZone.tzs, curBoundsGeometry) const intersectedZones = result.intersectedZones const numberOfZonesThatContainBounds = result.numberOfZonesThatContainBounds // console.log('intersectedZones', intersectedZones.length, 'exact:', foundExactMatch) let zoneResult: any = -1 // defaults to no zones found // check the results if ( intersectedZones.length === numberOfZonesThatContainBounds && numberOfZonesThatContainBounds > 0 ) { // analysis zones can fit completely within current quad zoneResult = intersectedZones } else if (intersectedZones.length > 0) { zoneResult = writeUnindexableData( { curBoundsGeometry, curZone, intersectedZones, }, geoDatFd ) } if (zoneResult !== -1) { _.set(data.lookup, curZone.id, zoneResult) } else { _.unset(data.lookup, curZone.id) } } fs.closeSync(geoDatFd) console.log('writing index file') fs.writeFile(dataDir + '/index.json', JSON.stringify(data), callback) } <file_sep>import * as fs from 'fs' import * as path from 'path' import { decode } from 'geobuf' import inside from '@turf/boolean-point-in-polygon' import { point } from '@turf/helpers' import Pbf from 'pbf' import { getTimezoneAtSea, oceanZones } from './oceanUtils' const tzData = require('../data/index.json') const FEATURE_FILE_PATH = path.join(__dirname, '..', 'data', 'geo.dat') let featureCache type CacheOptions = { /** * If set to true, all features will be loaded into memory to shorten future lookup * times. */ preload?: boolean /** * Must be a map-like object with a `get` and `set` function. */ store?: any } /** * Set caching behavior. * * @param {CacheOptions} options cachine options. */ function cacheLevel(options?: CacheOptions) { if ( options && options.store && typeof options.store.get === 'function' && typeof options.store.set === 'function' ) { featureCache = options.store } else { featureCache = new Map() } if (options && options.preload) { const featureFileFd = fs.openSync(FEATURE_FILE_PATH, 'r') if (featureFileFd < 0) { throw new Error('Failed to open geo.dat file') } _preCache(featureFileFd) fs.closeSync(featureFileFd) } } cacheLevel() /** * A function that will load all features into an unexpiring cache * * @param {number} featureFileFd * @returns {void} */ function _preCache(featureFileFd: number) { // shoutout to github user @magwo for an initial version of this recursive function function preloadFeaturesRecursive(curTzData, quadPos: string) { if (curTzData.pos >= 0 && curTzData.len) { const geoJson = loadFeatures( quadPos, curTzData.pos, curTzData.len, featureFileFd ) featureCache.set(quadPos, geoJson) } else if (typeof curTzData === 'object') { Object.getOwnPropertyNames(curTzData).forEach(function (value) { preloadFeaturesRecursive(curTzData[value], quadPos + value) }) } } preloadFeaturesRecursive(tzData.lookup, '') } /** * Load features from geo.dat at offset pos with length len. * Optionally accept a file descriptor * * @param quadPos * @param pos * @param len * @param fd * @returns the GeoJSON features in within the given quad region as defined in the * feature file data. */ function loadFeatures( quadPos: string, pos: number, len: number, fd: number = -1 ) { let featureFileFd = fd if (featureFileFd < 0) { featureFileFd = fs.openSync(FEATURE_FILE_PATH, 'r') if (featureFileFd < 0) { throw new Error('Failed to open geo.dat file') } } // exact boundaries saved in file // parse geojson for exact boundaries const buf = Buffer.alloc(len) const bytesRead = fs.readSync(featureFileFd, buf, 0, len, pos) // close featureFileFd if we opened it if (fd < 0) { fs.closeSync(featureFileFd) } if (bytesRead < len) { throw new Error( `tried to read ${len} bytes from geo.dat but only got ${bytesRead} bytes` ) } const data = new Pbf(buf) return decode(data) } /** * Find the timezone ID(s) at the given GPS coordinates. * * @param lat latitude (must be >= -90 and <=90) * @param lon longitue (must be >= -180 and <=180) * @returns An array of string of TZIDs at the given coordinate. */ export function find(lat: number, lon: number): string[] { const originalLon = lon let err // validate latitude if (isNaN(lat) || lat > 90 || lat < -90) { err = new Error('Invalid latitude: ' + lat) throw err } // validate longitude if (isNaN(lon) || lon > 180 || lon < -180) { err = new Error('Invalid longitude: ' + lon) throw err } // North Pole should return all ocean zones if (lat === 90) { return oceanZones.map((zone) => zone.tzid) } // fix edges of the world if (lat >= 89.9999) { lat = 89.9999 } else if (lat <= -89.9999) { lat = -89.9999 } if (lon >= 179.9999) { lon = 179.9999 } else if (lon <= -179.9999) { lon = -179.9999 } const pt = point([lon, lat]) const quadData = { top: 89.9999, bottom: -89.9999, left: -179.9999, right: 179.9999, midLat: 0, midLon: 0, } let quadPos = '' let curTzData = tzData.lookup while (true) { // calculate next quadtree position let nextQuad if (lat >= quadData.midLat && lon >= quadData.midLon) { nextQuad = 'a' quadData.bottom = quadData.midLat quadData.left = quadData.midLon } else if (lat >= quadData.midLat && lon < quadData.midLon) { nextQuad = 'b' quadData.bottom = quadData.midLat quadData.right = quadData.midLon } else if (lat < quadData.midLat && lon < quadData.midLon) { nextQuad = 'c' quadData.top = quadData.midLat quadData.right = quadData.midLon } else { nextQuad = 'd' quadData.top = quadData.midLat quadData.left = quadData.midLon } // console.log(nextQuad) curTzData = curTzData[nextQuad] // console.log() quadPos += nextQuad // analyze result of current depth if (!curTzData) { // no timezone in this quad, therefore must be timezone at sea return getTimezoneAtSea(originalLon) } else if (curTzData.pos >= 0 && curTzData.len) { // get exact boundaries let geoJson = featureCache.get(quadPos) if (!geoJson) { geoJson = loadFeatures(quadPos, curTzData.pos, curTzData.len) featureCache.set(quadPos, geoJson) } const timezonesContainingPoint = [] for (let i = 0; i < geoJson.features.length; i++) { if (inside(pt, geoJson.features[i])) { timezonesContainingPoint.push(geoJson.features[i].properties.tzid) } } // if at least one timezone contained the point, return those timezones, // otherwise must be timezone at sea return timezonesContainingPoint.length > 0 ? timezonesContainingPoint : getTimezoneAtSea(originalLon) } else if (curTzData.length > 0) { // exact match found return curTzData.map((idx) => tzData.timezones[idx]) } else if (typeof curTzData !== 'object') { // not another nested quad index, throw error err = new Error('Unexpected data type') throw err } // calculate next quadtree depth data quadData.midLat = (quadData.top + quadData.bottom) / 2 quadData.midLon = (quadData.left + quadData.right) / 2 } } export { cacheLevel as setCache } /** * Load all features into memory to speed up future lookups. */ export function preCache() { cacheLevel({ preload: true }) } <file_sep>type OceanZone = { left: number right: number tzid: string } export const oceanZones: OceanZone[] = [ { tzid: 'Etc/GMT-12', left: 172.5, right: 180 }, { tzid: 'Etc/GMT-11', left: 157.5, right: 172.5 }, { tzid: 'Etc/GMT-10', left: 142.5, right: 157.5 }, { tzid: 'Etc/GMT-9', left: 127.5, right: 142.5 }, { tzid: 'Etc/GMT-8', left: 112.5, right: 127.5 }, { tzid: 'Etc/GMT-7', left: 97.5, right: 112.5 }, { tzid: 'Etc/GMT-6', left: 82.5, right: 97.5 }, { tzid: 'Etc/GMT-5', left: 67.5, right: 82.5 }, { tzid: 'Etc/GMT-4', left: 52.5, right: 67.5 }, { tzid: 'Etc/GMT-3', left: 37.5, right: 52.5 }, { tzid: 'Etc/GMT-2', left: 22.5, right: 37.5 }, { tzid: 'Etc/GMT-1', left: 7.5, right: 22.5 }, { tzid: 'Etc/GMT', left: -7.5, right: 7.5 }, { tzid: 'Etc/GMT+1', left: -22.5, right: -7.5 }, { tzid: 'Etc/GMT+2', left: -37.5, right: -22.5 }, { tzid: 'Etc/GMT+3', left: -52.5, right: -37.5 }, { tzid: 'Etc/GMT+4', left: -67.5, right: -52.5 }, { tzid: 'Etc/GMT+5', left: -82.5, right: -67.5 }, { tzid: 'Etc/GMT+6', left: -97.5, right: -82.5 }, { tzid: 'Etc/GMT+7', left: -112.5, right: -97.5 }, { tzid: 'Etc/GMT+8', left: -127.5, right: -112.5 }, { tzid: 'Etc/GMT+9', left: -142.5, right: -127.5 }, { tzid: 'Etc/GMT+10', left: -157.5, right: -142.5 }, { tzid: 'Etc/GMT+11', left: -172.5, right: -157.5 }, { tzid: 'Etc/GMT+12', left: -180, right: -172.5 }, ] /** * Find the Etc/GMT* timezone name(s) corresponding to the given longitue. * * @param lon The longitude to analyze * @returns An array of strings of TZIDs */ export function getTimezoneAtSea(lon: number): string[] { // coordinates along the 180 longitude should return two zones if (lon === -180 || lon === 180) { return ['Etc/GMT+12', 'Etc/GMT-12'] } const tzs = [] for (let i = 0; i < oceanZones.length; i++) { const z = oceanZones[i] if (z.left <= lon && z.right >= lon) { tzs.push(z.tzid) } else if (z.right < lon) { break } } return tzs } <file_sep>import * as fs from 'fs' import * as path from 'path' import async from 'async' import { https } from 'follow-redirects' import yauzl from 'yauzl' import indexGeoJSON from './geo-index' const TARGET_INDEX_PERCENT = 0.75 const dlFile = path.join(__dirname, '..', 'downloads', 'timezones.zip') const tzFile = path.join(__dirname, '..', 'downloads', 'timezones.json') const downloadLatest = function (callback) { console.log('Downloading geojson') async.auto( { getLatestUrl: function (cb) { console.log('Downloading latest release metadata') https .get( { headers: { 'user-agent': 'node-geo-tz' }, host: 'api.github.com', path: '/repos/evansiroky/timezone-boundary-builder/releases/latest', }, function (res) { let data = '' res.on('data', function (chunk) { data += chunk }) res.on('end', function () { const parsed = JSON.parse(data) for (let i = 0; i < parsed.assets.length; i++) { if ( parsed.assets[i].browser_download_url.indexOf( 'timezones.geojson' ) > -1 ) { return cb(null, parsed.assets[i].browser_download_url) } } cb(new Error('geojson not found')) }) } ) .on('error', cb) }, rm: function (cb) { // fs.rm requires node v14+, so this will cause CI failures on node v12 fs.rm(dlFile, { force: true, recursive: true }, cb) }, mkdir: [ 'rm', function (results, cb) { fs.mkdir( path.join(__dirname, '..', 'downloads'), { recursive: true }, cb ) }, ], dl: [ 'mkdir', 'getLatestUrl', function (results, cb) { console.log('Downloading latest release data') https .get( { headers: { 'user-agent': 'node-geo-tz' }, host: 'github.com', path: results.getLatestUrl.replace('https://github.com', ''), }, function (response) { const file = fs.createWriteStream(dlFile) response.pipe(file) file.on('finish', function () { file.close(cb) }) } ) .on('error', cb) }, ], }, callback ) } export default function (cfg, callback) { if (!callback) { if (typeof cfg === 'function') { callback = cfg cfg = {} } else { callback = function () {} } } const resolvedDataDir = cfg.dataDir ? path.join(__dirname, '..', cfg.dataDir) : path.join(__dirname, '..', 'data') async.auto( { // download latest geojson data downloadData: function (cb) { downloadLatest(cb) }, deleteIndexFoldersAndFiles: [ 'downloadData', function (results, cb) { async.each( ['geo.dat', 'index.json'], function (fileOrFolder, eachCb) { // fs.rm requires node v14+, so this will cause CI failures on node v12 fs.rm( resolvedDataDir + '/' + fileOrFolder, { force: true, recursive: true }, eachCb ) }, cb ) }, ], unzipGeoJson: [ 'downloadData', function (results, cb) { yauzl.open(dlFile, { lazyEntries: true }, function (err, zipfile) { if (err) { return cb(err) } zipfile.readEntry() zipfile.on('entry', function (entry) { if (/\/$/.test(entry.fileName)) { // directory, keep reading zipfile.readEntry() } else { // assuming a json file zipfile.openReadStream(entry, function (err, readStream) { if (err) { return cb(err) } readStream.pipe(fs.createWriteStream(tzFile)) readStream.on('end', function () { zipfile.readEntry() }) }) } }) zipfile.on('end', function (err) { cb(err) }) }) }, ], createIndex: [ 'deleteIndexFoldersAndFiles', 'unzipGeoJson', function (results, cb) { indexGeoJSON( require(tzFile), resolvedDataDir, TARGET_INDEX_PERCENT, cb ) }, ], }, callback ) } <file_sep>/* globals describe, it */ import { assert } from 'chai' import { find, preCache } from '../src/find' import { oceanZones } from '../src/oceanUtils' const issueCoords = require('./fixtures/issues.json') process.chdir('/tmp') /** * Assert that a lookup includes certain timezones * * @param {number} lat * @param {number} lon * @param {string | array} tzs can be a string or array of timezone names */ function assertTzResultContainsTzs(lat, lon, tzs) { if (typeof tzs === 'string') { tzs = [tzs] } const result = find(lat, lon) assert.isArray(result) assert.sameMembers(result, tzs) } describe('find tests', function () { it('should find the timezone name for a valid coordinate', function () { assertTzResultContainsTzs(47.650499, -122.35007, 'America/Los_Angeles') }) it('should find the timezone name for a valid coordinate via subfile examination', function () { assertTzResultContainsTzs(1.44, 104.04, 'Asia/Singapore') }) it('should return Etc/GMT timezone for coordinate in ocean', function () { assertTzResultContainsTzs(0, 0, 'Etc/GMT') }) it('should return both timezones on an ocean coordinate at -180 longitude', function () { assertTzResultContainsTzs(40, -180, ['Etc/GMT-12', 'Etc/GMT+12']) }) it('should return both timezones on an ocean coordinate at +180 longitude', function () { assertTzResultContainsTzs(40, 180, ['Etc/GMT-12', 'Etc/GMT+12']) }) it('should return only one timezone on an ocean coordinate at +179.9999 longitude', function () { assertTzResultContainsTzs(40, 179.9999, 'Etc/GMT-12') }) it('should return only one timezones on an ocean coordinate at -179.9999 longitude', function () { assertTzResultContainsTzs(40, -179.9999, 'Etc/GMT+12') }) it('should return both timezone for coordinate in ocean on middle of boundary', function () { assertTzResultContainsTzs(40, -157.5, ['Etc/GMT+10', 'Etc/GMT+11']) }) it('should return all ocean timezones for coordinate at the North Pole', function () { assertTzResultContainsTzs( 90, 0, oceanZones.map((zone) => zone.tzid) ) }) describe('issue cases', function () { issueCoords.forEach(function (spot) { const spotDescription = spot.zids ? spot.zids.join(' and ') : spot.zid it( 'should find ' + spotDescription + ' (' + spot.description + ')', function () { assertTzResultContainsTzs(spot.lat, spot.lon, spot.zid || spot.zids) } ) }) }) describe('performance aspects', function () { this.timeout(20000) const europeTopLeft = [56.432158, -11.9263934] const europeBottomRight = [39.8602076, 34.9127951] const count = 2000 const findRandomPositions = function () { const timingStr = 'find tz of ' + count + ' random european positions' console.time(timingStr) for (let i = 0; i < count; i++) { find( europeTopLeft[0] + Math.random() * (europeBottomRight[0] - europeTopLeft[0]), europeTopLeft[1] + Math.random() * (europeBottomRight[1] - europeTopLeft[1]) ) } console.timeEnd(timingStr) } it( 'should find timezone of ' + count + ' random european positions with on-demand caching', findRandomPositions ) it( 'should find timezone of ' + count + ' random european positions with precache', function () { preCache() findRandomPositions() } ) }) }) <file_sep>/* globals afterEach, beforeEach, describe, it */ import * as fs from 'fs' import * as path from 'path' import { assert } from 'chai' import nock from 'nock' import { createDataDir, destroyDataDir } from './util' import update from '../src/update' const TEST_DATA_DIR = './data-test-update' const resolvedDataDir = path.join(__dirname, '..', TEST_DATA_DIR) const LOCAL_FOLDER = path.join(__dirname, '..', 'tests', 'fixtures') describe('data update', function () { this.timeout(4000) this.slow(2000) beforeEach(function (done) { createDataDir(resolvedDataDir, done) }) afterEach(function (done) { destroyDataDir(resolvedDataDir, done) }) it('tz geojson should get updated after fetching valid shapefile', function (done) { const aWhileAgo = new Date().getTime() - 100000 const latestRepoMock = { assets: [ { browser_download_url: 'https://github.com/evansiroky/timezone-boundary-builder/releases/download/2016d/timezones.geojson.zip', }, ], } const githubApiScope = nock('https://api.github.com') .get('/repos/evansiroky/timezone-boundary-builder/releases/latest') .reply(200, JSON.stringify(latestRepoMock)) const githubDlScope = nock('https://github.com') .get( '/evansiroky/timezone-boundary-builder/releases/download/2016d/timezones.geojson.zip' ) .replyWithFile(200, path.join(LOCAL_FOLDER, 'dist.zip')) const doneHelper = function (err?: Error) { githubApiScope.done() githubDlScope.done() done(err) } // update timezone data by downloading it and extracting to geojson update( { dataDir: TEST_DATA_DIR, }, function (err) { try { assert.isNotOk(err) } catch (e) { return doneHelper(e) } // check for geojson file existence fs.stat(resolvedDataDir + '/index.json', function (err, stats) { try { assert.isNotOk(err) assert.isAbove( stats.ctime.getTime(), aWhileAgo, 'file update time is before test!' ) } catch (e) { return doneHelper(e) } doneHelper() }) } ) }) }) <file_sep>import update from '../src/update' update( (err) => { if (err) { console.log('update unsuccessful. Error: ', err) } else { console.log('update successfully completed') } }, () => {} ) <file_sep>import * as fs from 'fs' import async from 'async' export function createDataDir(dir, callback) { async.auto( { destroyDataDir: (cb) => { destroyDataDir(dir, cb) }, createNewDataDir: [ 'destroyDataDir', function (results, cb) { fs.mkdir(dir, { recursive: true }, cb) }, ], }, callback ) } export function destroyDataDir(dir, callback) { async.each( [dir, dir + '.zip'], // fs.rm requires node v14+, so this will cause CI failures on node v12 (dir, cb) => fs.rm(dir, { force: true, recursive: true }, cb), callback ) } <file_sep># node-geo-tz [![npm version](https://badge.fury.io/js/geo-tz.svg)](http://badge.fury.io/js/geo-tz) [![Build Status](https://travis-ci.org/evansiroky/node-geo-tz.svg?branch=master)](https://travis-ci.org/evansiroky/node-geo-tz) [![Dependency Status](https://david-dm.org/evansiroky/node-geo-tz.svg)](https://david-dm.org/evansiroky/node-geo-tz) [![Test Coverage](https://img.shields.io/codecov/c/github/evansiroky/node-geo-tz.svg)](https://codecov.io/github/evansiroky/node-geo-tz) The most up-to-date and accurate node.js geographical timezone lookup package. It's fast too! ## Install `npm install geo-tz` ## Usage ```js const { find } = require('geo-tz') find(47.650499, -122.350070) // ['America/Los_Angeles'] find(43.839319, 87.526148) // ['Asia/Shanghai', 'Asia/Urumqi'] ``` ## API Docs: As of Version 7, there is no longer a default import. The `find` function should be used instead. As of Version 5, the API now returns a list of possible timezones. There are certain coordinates where the timekeeping method will depend on the person you ask. Also, another case where 2 or more timezones could be returned is when a request is made with a coordinate that happens to be exactly on the border between two or more timezones. ### find(lat, lon) Returns the timezone names found at `lat`, `lon`. The timezone names will be the timezone identifiers as defined in the [timezone database](https://www.iana.org/time-zones). The underlying geographic data is obtained from the [timezone-boudary-builder](https://github.com/evansiroky/timezone-boundary-builder) project. This library does an exact geographic lookup which has tradeoffs. It is perhaps a little bit slower that other libraries, has a larger installation size on disk and cannot be used in the browser. However, the results are more accurate than other libraries that compromise by approximating the lookup of the data. The data is indexed for fast analysis by caching subregions of geographic data when a precise lookup is needed. ### setCache(options) By default, geoTz lazy-loads exact lookup data into an unexpiring cache. The `setCache` method can be used to change the caching behavior using the following options: * `preload` - if set to true will attempt to cache all files (slow startup time and requires lots of memory) * `store` - offload the cache to a custom storage solution (must be compatible with the Map api) Examples: ```js setCache({ preload: true }) // preloads all files let map = new Map(); setCache({ store: map }) // pass a Map-like storage object ``` ## Limitations This library is not intended to be used in the browser due to the large amount of files that are included to perform exact geographic lookups. ## An Important Note About Maintenance Due to the ever-changing nature of timezone data, it is critical that you always use the latest version of this package. If you use old versions, there will be a few edge cases where the calculated time is wrong. If you use greenkeeper, please be sure to specify an exact target version so you will always get PR's for even patch-level releases. <file_sep>/* globals afterEach, beforeEach, describe, it */ import * as fs from 'fs' import * as path from 'path' import { assert } from 'chai' import geobuf from 'geobuf' import Pbf from 'pbf' import { createDataDir, destroyDataDir } from './util' import createGeoIndex from '../src/geo-index' const TEST_DATA_DIR = path.join(__dirname, '..', 'data-test-geoindex') const TEST_GEO_DAT = `${TEST_DATA_DIR}/geo.dat` const TEST_INDEX_FILE = `${TEST_DATA_DIR}/index.json` const testTzData = require('./fixtures/largeTz.json') const expectedIndexData = require('./fixtures/expectedIndexData.json') /** * Synchronously extracts data from the given subzoneFile and verifies that it * matches the passed expectedData. * * @param {number} pos * @param {number} len * @param {object} expectedData * @returns {void} */ function assertSubzoneDataIsEqual(pos, len, expectedData) { const fd = fs.openSync(TEST_GEO_DAT, 'r') const buf = Buffer.alloc(len) fs.readSync(fd, buf, 0, len, pos) fs.closeSync(fd) const data = new Pbf(buf) assert.deepEqual(geobuf.decode(data), expectedData) } describe('geoindex', function () { beforeEach(function (done) { createDataDir(TEST_DATA_DIR, done) }) afterEach(function (done) { destroyDataDir(TEST_DATA_DIR, done) }) it('should create geoindex of simple geometry', function (done) { this.timeout(4000) this.slow(2000) createGeoIndex(testTzData, TEST_DATA_DIR, 0.99, function (err) { assert.isNotOk(err) const generatedIndex = require(TEST_INDEX_FILE) assert.deepEqual(generatedIndex, expectedIndexData) const zone1 = generatedIndex.lookup.b.b.d.c.d.d // also make sure certain subzone data is written assertSubzoneDataIsEqual( zone1.pos, zone1.len, require('./fixtures/expectedSubzone1.json') ) const zone2 = generatedIndex.lookup.b.c.a.a.a.d assertSubzoneDataIsEqual( zone2.pos, zone2.len, require('./fixtures/expectedSubzone2.json') ) done() }) }) })
0fd7adc8d2f91fbd7bdb8daa90e2c895acb89373
[ "Markdown", "TypeScript" ]
10
TypeScript
evansiroky/node-geo-tz
0608027787cf39b69214bfe0e4ba9e2ff6ff4edb
9969098b826db4f464a99ab9c2379ce5a66b75f2
refs/heads/master
<file_sep>import java.util.Iterator; import java.util.LinkedList; public class LinkedlistPrac { public void getlinkedlistprac(){ LinkedList linkedList = new LinkedList(); linkedList.add("A"); linkedList.add("B"); linkedList.add("B"); linkedList.add("C"); System.out.println(linkedList); getIteratedItems(linkedList); } public void getIteratedItems(LinkedList linkedList){ Iterator iterator = linkedList.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } } <file_sep>import java.util.ArrayList; import java.util.LinkedList; public class Main { public static void main(String[] args) { ListsetbPrac listsetbPrac = new ListsetbPrac(); listsetbPrac.getListsetbPrac(); LinkedlistPrac linkedlistPrac = new LinkedlistPrac(); linkedlistPrac.getlinkedlistprac(); setPrac setPrac = new setPrac(); setPrac.getsetPrac(); ArrayList<Integer> integerArrayList = listsetbPrac.getInteger(); for(Integer integer : integerArrayList) System.out.println(integer); StudentController studentController = new StudentController(); for (Student student : studentController.getStudentList()){ System.out.println(student.getStudentId()); System.out.println(student.getStudentName()); System.out.println(student.getSection()); System.out.println(); } MapPrac mapPrac = new MapPrac(); mapPrac.getMap(); } } <file_sep>import java.util.Map; import java.util.TreeMap; public class MapPrac { public void getMap(){ Map map = new TreeMap(); map.put(1,"A"); map.put(2,"B"); System.out.println(map); } }
aa329ec9183c31a90c3e73acae2b7ee9c93e76d2
[ "Java" ]
3
Java
SifatNawrinNova/Collection
e6f2fddd06df58e52c7429266bc87e28a81d19a1
e349cae95a549777bc6b950eff5778d97f8c4625
refs/heads/master
<file_sep>import React, {Component} from 'react'; import Specie from './specie'; import './styles.css'; import {api} from '../../services/api'; export default class Main extends Component { state = { stPkmnList: [], fetched: false }; componentDidMount() { this.listPkmn(); } listPkmn = async () => { const { data } = await api.get('pokemon/?limit=21'); this.setState({stPkmnList: data.results, fetched: true}); }; render() { const lista = this.state.stPkmnList; return ( <div className="pkmn-list"> {lista.map((l,i) => ( <Specie key={i} id={i+1} pkmn={l} /> ))} </div> ); } }<file_sep>import React, {Component} from 'react'; import { api } from '../../services/api'; import './styles.css'; export default class Detail extends Component { state = { detail: {}, image: {} }; async componentWillMount() { const { id } = this.props.match.params; const { data } = await api.get(`pokemon/${id}`); this.setState({detail: data, image: data.sprites}); }; getTypes = (types) => { const pkmnTypes = []; for (let key in types) { pkmnTypes.push(types[key].type.name); } return pkmnTypes; }; render() { const { name, types, id } = this.state.detail; const PkmnType = this.getTypes(types); return ( <div className="container"> <img src={this.state.image.front_default} /> <div className="container-detail"> <h2>{name}</h2> {PkmnType.map(type => ( <p key={type} className="badge">{type}</p> ))} </div> </div> ); } }
085e7764676bcfce76477b19ac90f9c5dc66fcff
[ "JavaScript" ]
2
JavaScript
dalcarobo/pkmn-api-test-react
1a93d14097e0d830c5aa6098aea8cadce1031c40
503e3941a005c67b52ee204d4725304ea09b07d9
refs/heads/master
<file_sep>## 1、可变与不可变 String类中使用字符数组保存字符串,有final修饰符,因此string对象不可变。 StringBuffer和StringBuilder都继承自AbstractStringBuilder类,也是使用字符数组保存字符串,但是没有final字符修饰,因此可变 ### 问题:如何在不重新分配内存地址的情况下修改string对象? 利用Java的反射机制(final只对编译有效,对运行无效,因此可以在运行时改变final的内容。) ## 2、是否多线程安全 String是不可变的,可以理解为常量,因此是线程安全的。 StringBuilder对方法增加了同步锁或者对调用的方法加了同步锁,因此是线程安全的。 StringBuffer没有对方法进行加同步锁,所以是非线程安全的。 ## 3、StringBuilder与StringBuffer共同点 共同点:有公共父类AbstractStringBuffer 两者的方法都会调用父类中的公共方法,但是StringBuilder对在方法上加synchronized关键字,加上同步锁。 如果程序不是多线程的,StringBuilder的运行效率高于StringBuffer。 ## 4、使用总结 1.如果要操作少量的数据用 = String 2.单线程操作字符串缓冲区 下操作大量数据 = StringBuilder 3.多线程操作字符串缓冲区 下操作大量数据 = StringBuffer ## 5、抽象类和接口的区别: 抽象类中可以定义一些子类的公共方法,子类字需要增加新的功能,不需要重复写已经存在的方法; 接口知识对方法的声明和常量的定义。 <file_sep>package LinkedList; import java.util.Hashtable; import javax.swing.text.TabableView; /** * Given a circular linked list, implement an algorithm which returns node at the beginning of the loop DEFINITION Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list EXAMPLE Input: A -> B -> C -> D -> E -> C [the same C as earlier] Output: C * @author Chi * * * * 核心问题:发现循环开始的地方 * 定义:什么是循环开始的地方?第一个重复出现的节点。 * 问题转化:记录访问过的节点,判断当前节点是否出现在访问记录里 * 问题1:如何存储访问记录:hashtable *技巧1:记录访问记录 * * *技巧2:使用两个不同移动速度的指针(双指针策略) * */ public class FindBeginning { public static LinkedListNode findBeginning(LinkedListNode head) { Hashtable<Integer, Boolean> table = new Hashtable<>(); LinkedListNode begin = null; while(head != null){ if (table.containsKey(head.data)) { begin = head; } table.put(head.data, true); head = head.next; } return begin; } public static LinkedListNode findBeginning2(LinkedListNode head) { LinkedListNode n1 = head; LinkedListNode n2 = head; while (n2.next != null) { System.out.println(n2.data); n1 = n1.next; n2 = n2.next.next; if (n1 == n2) { break; } } if (n2.next == null) { return null; } n1 = head; while (n1 != n2) { n1 = n1.next; n2 = n2.next; } return n2; } public static void main(String[] args) { // TODO Auto-generated method stub LinkedListNode two = new LinkedListNode(9); LinkedListNode three = new LinkedListNode(1); LinkedListNode four = new LinkedListNode(2); LinkedListNode five = new LinkedListNode(4); LinkedListNode six = new LinkedListNode(3); LinkedListNode seven = new LinkedListNode(1); two.next = three; three.next = four; four.next = five; five.next = six; six.next = seven; LinkedListNode begin = findBeginning(two); System.out.println(begin.data); } } <file_sep>package LinkedList; /** * You have two numbers represented by a linked list, where each node contains a single digit The digits are stored in reverse order, such that the 1’s digit is at the head of the list Write a function that adds the two numbers and returns the sum as a linked list * @author Chi * * 核心问题:逆序进行加法运算 * 问题背景:1、模拟日常的加法运算(逆序进行),因此需要记录(进位数字) * 2、两个链表的长度是否一致? * */ public class AddLists { public static LinkedListNode addlists(LinkedListNode l1, LinkedListNode l2, int carry) { if(l1 == null && l2 == null){ // 递归边界条件 return null; } LinkedListNode result = new LinkedListNode(carry); int value = carry; if(l1 != null){ value += l1.data; } if(l2 != null){ value += l2.data; } result.data = value % 10; LinkedListNode more = addlists( l1 == null ?null : l1.next , l2 == null ? null:l2.next, value > 10 ? 1:0); result.next = more; return result; } public static void main(String[] args) { // TODO Auto-generated method stub LinkedListNode two = new LinkedListNode(9); LinkedListNode three = new LinkedListNode(8); LinkedListNode four = new LinkedListNode(2); LinkedListNode five = new LinkedListNode(4); LinkedListNode six = new LinkedListNode(3); LinkedListNode seven = new LinkedListNode(1); // 134 + 289 = 423 two.next = three; three.next = four; five.next = six; six.next = seven; LinkedListNode result = addlists(two, five, 0); while (result != null) { System.out.println(result.data); result = result.next; } } } <file_sep>package ArrayAndString; /** * Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer NOTE: One or two additional variables are fine An extra copy of the array is not * @author Chi * * *问题1:不能使用additional buffer时什么意思? *问题2:可否使用固定长度的数组 * * */ public class RemoveDuplicates { /* * 就地解决问题:不能使用其他数组 * 问题分析: * 1、问题明确:删除一个字符串中所有的重复字符,只保留非重复的字符 * 字符串是一个什么样的字符串:空字符串,长度为1,长度大于1 * 2、问题背景:不能使用其他辅助数组等; * 3、Java中的字符串不可变,因此需要使用辅助的结构 * 4、尾指针的用法:从开头到尾指针中间的 内容是没有重复的,判断其他字符是否在其中。 */ private static String remove(String str){ if (str == null) { return null; } if(str.length() < 2){ return str; } int tail = 1; char[] char_set = str.toCharArray(); for(int i = 1; i < str.length(); i++){ int j; for(j = 0; j < tail; j++){ if (char_set[i] == char_set[j]) { char_set[i] = '\0'; } } if(j == tail){ char_set[tail] = char_set[i]; tail += 1; } } return new String(char_set); } public static void main(String[] args) { // TODO Auto-generated method stub String a = "abcdefg"; String b = "accbd"; String c = ""; String d = "a"; String e = "aaabbb"; System.out.println(remove(a)); System.out.println(remove(b)); System.out.println(remove(c)); System.out.println(remove(d)); System.out.println(remove(e)); } } <file_sep>package LinkedList; /** * Implement an algorithm to find the nth to last element of a * singly linked list * * 核心问题:在单向链表中找到倒数第n个到最后一个元素。 * 问题背景:单向链表数组:之后一个next指向 * 倒数第n个到最后一个元素(当链表中的元素少于n时如何处理?) * *问题转化:假设链表中节点的个数大于n,如何找到倒数第n个元素? *思路:双指针方法:两个指针间的距离为n,当一个指针达到最后时,另一个指针指向倒数第n个元素 * *技巧:双指针方法,指针之间距离固定。 * * *递归方法: * * */ public class NthToLast { public static LinkedListNode nthToLast(LinkedListNode head, int nth) { LinkedListNode prevous = head; LinkedListNode current = head; for(int i = 0; i < nth-1; i++){ if (current == null) { return null; } current = current.next; } while(current.next != null){ prevous = prevous.next; current = current.next; } return prevous; } public static void main(String[] args) { // TODO Auto-generated method stub LinkedListNode two = new LinkedListNode(2); LinkedListNode three = new LinkedListNode(1); LinkedListNode four = new LinkedListNode(3); LinkedListNode five = new LinkedListNode(1); LinkedListNode six = new LinkedListNode(3); two.next = three; three.next = four; four.next = five; five.next = six; LinkedListNode head = nthToLast(two, 2); while(head != null){ System.out.println(head.data); head = head.next; } } } <file_sep># CrackingTheCodingInterview <file_sep>package TreesAndGraphs; /** * Write an algorithm to find the 'next'node (i.e., in-order successor) of a given nodein a binary search tree. Youmay assume that each nodehas a link to its parent * @author Chi * *核心问题:中序遍历中当前节点的下一个节点 *问题背景:中序遍历:左子树-->当前节点-->右子树 * 已知当前节点,则其下一个节点位于右子树的最左边的节点, *问题分析:当前节点有右子树:找到右子树的最左节点 * 当前节点没有右子树:说明该子树已经遍历完,则需要找到一个节点使当前节点位于该节点的左子树。 * 当前节点为空,表示已经是最右节点,后继节点为空。 */ public class InorderSucc { public static TreeNode leftMostChild(TreeNode n) { if (n == null) { return null; } while(n.left != null){ n = n.left; } return n; } public static TreeNode inOrderSucc(TreeNode current) { if (current == null) { return null; } if (current.right != null) { return leftMostChild(current.right); }else{ TreeNode qNode = current; TreeNode xNode = qNode.parent; while(xNode != null && xNode.left != qNode){ qNode= xNode; xNode = xNode.parent; } return xNode; } } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode o = new TreeNode(1); TreeNode t = new TreeNode(2); TreeNode th = new TreeNode(3); TreeNode four = new TreeNode(4); TreeNode five = new TreeNode(5); TreeNode six = new TreeNode(6); TreeNode seven = new TreeNode(7); TreeNode eight = new TreeNode(8); TreeNode nine = new TreeNode(9); /** * 1 * 2 3 * 4 5 6 7 * 8 9 */ o.left = t; t.parent = o; o.right = th; th.parent = o; t.right = five; five.parent = t; four.parent = t; t.left = four; th.left = six; six.parent = th; th.right = seven; seven.parent = th; four.left = eight; eight.parent = five; four.right = nine; nine.parent = four; System.out.println(inOrderSucc(five).data); } } <file_sep>## 什么是图 图是一种这样的非线性结构:图由若干节点和边组成,任意两个“节点”都有可能通过“边”连接,因此任意两个节点之间都有可能存在一条路径。 关键词:非线性结构、节点、边、路径 问题1:什么是非线性结构?常用的非线性结构有哪些? 一个节点元素可能有多个直接前驱和多个直接后驱节点 常用的非线性结构:多维数组、广义表、树、图 问题2:什么是节点?边? 节点:一条边的终点或者多条边的公共互联点。 边:两个节点之间的联系 问题3:什么是线性结构?常用的线性结构有哪些? 有序数据元素的集合 常用的线性结构有:线性表、栈、队列、双队列、数组、串 ### 图的严格定义 图G=(V,E),是由节点的集合V和边的结合E构成的。一个图的所有节点构成一个集合V,一个变可以表示成(v1,v2)。 其中v1,v2属于V。 有向图:如果(v1,v2)有序,即边(v1,v2)和边(v2,v1)不同,则图是有向的(directed) 无向图:否则称之为无向图。 问题4:什么是路径?如何计算路径的长度?如何选择最佳路径? 路径(path)是图的一系列节点v1,v2,v3...vn,并且对于1<=i<n,都有(vi,vi+1)属于E(边的集合)。即路径是边 的集合,路径两端为起始和终止节点,路径边的(加权)数量和称路径的长度。两点之间可能存在多条路径,因此需要 选择一条(近似)最佳的路径。 环:如有一条长度大于0的路径,其两端为同一节点,则图中存在环路。 连通图:如果任意两个节点之间都存在至少一条路径,则图成为连通图 强连通图:有向图,连通图 弱连通图:有向图不连通,但是对应的无向图连通,称之为弱连通图。 ## 图有什么特性?(与线性表、树等结构相比)(为什么要有图) 结构松散,自由度较高,树是一种特殊的图 点的度:以该顶点作为端点的边的数量。有向图中又分为出度和入度。 顶点数、边数、度之间的关系:边的数量=(各个顶点的度数之和)/2 ## 什么场景下使用图?(图的使用范围) 存在1对多的联系 ## 如何实现图?如何遍历图 ### 邻接矩阵 逻辑结构分为两部分:V和E集合。因此,用一个一维数组存放图中所有顶点数据; 用一个二维数组存放顶点间关系(边或弧)的数据,这个二维数组称为邻接矩阵。邻接矩阵又分为有向图邻接矩阵和无向图邻接矩阵 邻接矩阵(Adjacency Matrix):是表示顶点之间相邻关系的矩阵。设G=(V,E)是一个图,其中V={v1,v2,…,vn}。 G的邻接矩阵是一个具有下列性质的n阶方阵: ①对无向图而言,邻接矩阵一定是对称的,而且主对角线一定为零(在此仅讨论无向简单图),副对角线不一定为0,有向图则不一定如此。 ②在无向图中,任一顶点i的度为第i列(或第i行)所有非零元素的个数,在有向图中顶点i的出度为第i行所有非零元素的个数, 而入度为第i列所有非零元素的个数。 ③用邻接矩阵法表示图共需要n^2个空间,由于无向图的邻接矩阵一定具有对称关系,所以扣除对角线为零外, 仅需要存储上三角形或下三角形的数据即可,因此仅需要n(n-1)/2个空间。 邻接矩阵的优点:简单易实现 缺点:空间复杂度为节点个数的平方,当节点数很多,但联系不是很密集时,使用邻接矩阵浪费空间。因此提出另外一种实现方法 ### 邻接表 即记录每个节点所有的相邻节点。对于节点m,我们建立一个链表。对于任意节点k, 如果有(m,k)∈E,就将该节点放入到对应节点m的链表中。邻接表是实现图的标准方式。 实现原理:数组用于存储节点,链表存储该数据元素所有的相邻元素。 优点:空间复杂度O(|V|+|E|),还可以附加其他边和节点的相关信息。 ###深度优先遍历和广度优先遍历 DFS: 深度优先搜索DFS遍历类似于树的前序遍历。其基本思路是: a) 假设初始状态是图中所有顶点都未曾访问过,则可从图G中任意一顶点v为初始出发点,首先访问出发点v,并将其标记为已访问过。 b) 然后依次从v出发搜索v的每个邻接点w,若w未曾访问过,则以w作为新的出发点出发,继续进行深度优先遍历,直到图中所有和v有路径相通的顶点都被访问到。 c) 若此时图中仍有顶点未被访问,则另选一个未曾访问的顶点作为起点,重复上述步骤,直到图中所有顶点都被访问到为止。 BFS: 广度优先搜索遍历BFS类似于树的按层次遍历。其基本思路是: a) 首先访问出发点Vi b) 接着依次访问Vi的所有未被访问过的邻接点Vi1,Vi2,Vi3,…,Vit并均标记为已访问过。 c) 然后再按照Vi1,Vi2,… ,Vit的次序,访问每一个顶点的所有未曾访问过的顶点并均标记为已访问过,依此类推,直到图中所有和初始出发点Vi有路径相通的顶点都被访问过为止。 ## 图相关其他算法 <file_sep>package TreesAndGraphs; import javax.xml.soap.Node; /** * Given a sorted (increasing order) array with unique integer elements, * write an algorithm to create a binary search tree with minimal height. * @author Chi * *核心问题:生成BST *问题背景:BST:左<根<右 * 有序(升序)数组:符合BST的特性 * 最小高度的树:左子树和右子树的节点数量尽可能的相等 * *策略分析:根据题目要求,把数组分为三部分,左中右三部分,左<中<右。中间一个元素作root,其他部分作为左子树和右子树 *左部分采用同样的策略构造其左子树右子树和根节点。因此可以考虑采用递归。 * *递归边界:数组的长度等于1, *递推阶段:root.left = fun(array_left),root.right = fun(array_right); */ public class CreateBST { public static TreeNode createBST(int[] array) { TreeNode root; int start = 0; int end = array.length - 1; int middle = array.length / 2; if (start == (end - 1)) { root = new TreeNode(array[end]); root.left = new TreeNode(array[start]); return root; } if (start == end) { root = new TreeNode(array[end]); return root; } root = new TreeNode(array[middle]); int[] left = new int[middle - start]; int[] right = new int[end - middle]; for(int i = 0; i < middle; i++){ left[i] = array[i]; } for(int j = middle + 1; j <= end; j++){ right[j-middle-1] = array[j]; } root.left = createBST(left); root.right = createBST(right); return root; } /** * 代码优化 * @param array * @param start * @param end * @return */ public static TreeNode createMinBST(int[] array, int start, int end) { if (end < start) { return null; } int middle = (start + end) / 2; TreeNode root = new TreeNode(array[middle]); root.left = createMinBST(array, start, middle-1); root.right = createMinBST(array, middle+1, end); return root; } public static void inOrder(TreeNode root) { if (root == null) { return; } TreeNode left = root.left; TreeNode right = root.right; inOrder(left); System.out.print(root.data + " "); inOrder(right); } public static int depth(TreeNode root) { //递归边界条件 if (root == null) { return 0; } int left = 1; int right = 1; left += depth(root.left); right += depth(root.right); return left > right ? left:right; } public static void main(String[] args) { // TODO Auto-generated method stub int[] array = {1,2,3,4,5,6}; TreeNode root = createBST(array); inOrder(root); System.out.println(); TreeNode node = createMinBST(array, 0, array.length-1); inOrder(node); System.out.println(depth(root)); System.out.println(depth(node)); } } <file_sep>package LinkedList; import java.awt.TexturePaint; import java.util.Hashtable; import LinkedList.LinkedListNode; public class DeleteDups { /** * Write code to remove duplicates from an unsorted linked list FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? */ /*** * 问题明确:删除链表中重复的节点 * 问题背景: 单向链表:通过指针获取下一个节点。 * 链表长度不固定:无法使用一个固定大小的数组记录那些节点是否重复 * 允许使用辅助数据结构如何操作? * 不允许使用数据结构时如何操作? * 问题转化:如何记录链表中已经访问过的节点的值,以便于后续访问能够发现是否重复? * 问题分析: 使用HashTable等键值对结构的,能够快速查找某一节点值是否包含已经包含在链表中。 * 问题转化:如何删除链表节点。 * 问题分析:删除的是当前节点,因此需要改变当前节点的上一个节点的指针指向。 * * step1:建立一个ehashtable, 建立两个指针:一个指向当前节点,一个指向当前节点的上一个节点。 * step2:遍历链表,判断当前节点的值是否包含在table中,如不含,则把该节点值放入tbale中 * 坨包含,则把当前节点上一个节点的指针指向当前节点的下一个节点。 * @param head */ public static void deleteDups(LinkedListNode head) { LinkedListNode previous = null; Hashtable table = new Hashtable(); while(head != null){ if (table.containsKey(head.data)) { previous.next = head.next; }else{ table.put(head.data, true); previous = head; } head = head.next; } } // 当不使用table时,如何判断是否有重复的节点? /** * 双指针策略:一个代表当前指针、一个表示从head到当前指针 * @param args */ public static void deleteDups2(LinkedListNode head) { if (head == null) { } LinkedListNode prevoius = head; LinkedListNode current = prevoius.next; while(current!=null){ LinkedListNode runer = head; while(runer != current){ if (runer.data == current.data) { // runner和current节点值相同。 LinkedListNode temp = current.next; prevoius.next = temp; current = temp; break; } runer = runer.next; } if (runer == current) { prevoius = current; current = current.next; } } } public static void main(String[] args) { // TODO Auto-generated method stub LinkedListNode two = new LinkedListNode(2); LinkedListNode three = new LinkedListNode(1); LinkedListNode four = new LinkedListNode(3); LinkedListNode five = new LinkedListNode(1); LinkedListNode six = new LinkedListNode(3); two.next = three; three.next = four; four.next = five; five.next = six; deleteDups2(two); LinkedListNode head = two; while(head != null){ System.out.println(head.data); head = head.next; } } } <file_sep>package RecursionAndDP; public abstract class GetTime { public final void getTime(){ long start = System.currentTimeMillis(); long end = System.currentTimeMillis(); System.out.println("ÔËÐÐʱ¼ä£º" + (end-start) + "ºÁÃë"); } public abstract int runcode(); } <file_sep>package TreesAndGraphs; import javax.crypto.EncryptedPrivateKeyInfo; import javax.naming.spi.DirStateFactory.Result; import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction; import TreesAndGraphs.TreeNode; /** * Implement a function to check if a tree is balanced For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one * @author Chi * * 核心问题:检查一个树是否是平衡树 * 问题背景:平衡树:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。 * 树的深度:根节点到叶子节点的距离(层数) * 问题分析:任意两个叶子节点到根节点的距离差不超过1,则最深的和最浅子树高度差不超过1. * 问题转化:如何找打一个数的深度 * 问题分析:若树为空,则深度为0 * 若树不为空,则深度=1+max(左子树,右子树) * 因此,计算树的深度是一个递归过程 * 如何设计递归:递归边界条件:root==null * 递推公式:1+max(root.left,root.right) * * */ public class IsBalanced { private static int maxDepth(TreeNode root){ if (root == null) { return 0; } return 1+Math.max(maxDepth(root.left),maxDepth(root.right)); } private static int minDepth(TreeNode root) { if (root == null) { return 0; } return 1+Math.min(minDepth(root.left), minDepth(root.right)); } private static boolean isBalanced(TreeNode root) { return (maxDepth(root) - minDepth(root)) <= 1; } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode o = new TreeNode(5); TreeNode t = new TreeNode(5); TreeNode th = new TreeNode(5); TreeNode four = new TreeNode(5); TreeNode five = new TreeNode(5); TreeNode six = new TreeNode(5); TreeNode seven = new TreeNode(5); TreeNode eight = new TreeNode(5); TreeNode nine = new TreeNode(5); o.left = t; o.right = th; t.right = five; t.left = four; th.left = six; th.right = seven; four.left = eight; four.right = nine; boolean Result = isBalanced(o); System.out.println(Result); } } <file_sep>package TreesAndGraphs; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * Given a binary tree, design an algorithm whichcreates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D,you'll have D linked lists * @author Chi * * 核心问题:二叉树的每一层构建一个链表。 * 问题背景:二叉树:每一个节点最多有两个子节点,中序遍历、先序、后序,层次遍历。 * 二叉树的层:层次遍历, * 策略分析:根据上一层的顺序获取下一层的节点。(BSF) * * 技巧:二叉树的层次遍历方法 * 根据上一层获取下一层的节点:不需要使用辅助的存储 * */ public class CreateLevelLinkedList { public static void clll(TreeNode root, ArrayList<LinkedList<TreeNode>> lists, int level) { if (root == null) { return; //边界条件 } LinkedList<TreeNode> list = null; if (lists.size() == level) { //当前层不在list中 list = new LinkedList<>(); lists.add(list); }else{ list = lists.get(level); } list.add(root); clll(root.left, lists, level+1); clll(root.right, lists, level+1); } public static void clll(TreeNode root) { ArrayList<LinkedList<TreeNode>> lists = new ArrayList<>(); clll(root, lists, 0); for (LinkedList<TreeNode> linkedList : lists) { for (TreeNode treeNode : linkedList) { System.out.print(treeNode.data); } System.out.println(); } } //根据树的特点构建的广度优先遍历方法:类似层次遍历。 public static ArrayList<LinkedList<TreeNode>> BSF(TreeNode root) { ArrayList<LinkedList<TreeNode>> lists = new ArrayList<>(); LinkedList<TreeNode> current = new LinkedList<>(); if (root != null) { current.add(root); } while(current.size()>0){ lists.add(current); LinkedList<TreeNode> parents = current; current = new LinkedList<>(); for(TreeNode parent: parents){ if (parent.left != null) { current.add(parent.left); } if (parent.right != null) { { current.add(parent.right); } } } } return lists; } public static void preOrder(TreeNode root) { if (root == null) { return; } System.out.print(root.data + " "); preOrder(root.left); preOrder(root.right); } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode o = new TreeNode(1); TreeNode t = new TreeNode(2); TreeNode th = new TreeNode(3); TreeNode four = new TreeNode(4); TreeNode five = new TreeNode(5); TreeNode six = new TreeNode(6); TreeNode seven = new TreeNode(7); TreeNode eight = new TreeNode(8); TreeNode nine = new TreeNode(9); /** * 1 * 2 3 * 4 5 6 7 * 8 9 */ o.left = t; o.right = th; t.right = five; t.left = four; th.left = six; th.right = seven; four.left = eight; four.right = nine; clll(o); ArrayList<LinkedList<TreeNode>> lists = BSF(o); for (LinkedList<TreeNode> linkedList : lists) { for (TreeNode treeNode : linkedList) { System.out.print(treeNode.data); } System.out.println(); } } } <file_sep>package TreesAndGraphs; import java.util.LinkedList; /** * Implement a function to check if a binary tree isa binary search tree * @author Chi * * 核心问题:判断二叉树是否是BST。 * 问题背景:二叉树:无序 * BST:左<根<右 * 树中是否有重复元素? * 策略分析:1、BST的中序遍历是有序的,因此可以使用中序遍历得到一个数组,判断该数组是否是有序的。 * 但当树中有重复值时,无法正确判断是否是BST。 * 2、根据BSTleft<root<right的特性。遍历所有节点,判断其子节点是否满足。(对迭代遍历方法做出修改) * */ public class IsBST { private static void inOrder(TreeNode root, LinkedList<Integer> array) { if (root == null) { return; } inOrder(root.left, array); array.add(root.data); inOrder(root.right, array); } public static boolean isBST(TreeNode root) { LinkedList<Integer> array = new LinkedList<>(); inOrder(root, array); int length = array.size(); for(int i = 0; i < length-1; i++){ if (array.get(i)>array.get(i+1)) { return false; } } return true; } /** * * 上一种方法分析: * 中序遍历得到的数组用于判断是否是BST,但是判断时仅适用上一个数字和下一个数字进行比较,是否可以保存上一个数字,从而不用保存整个数组, * 在获取下一个数字之后判断是否是BST。 * * 设计递归:边界条件:root=null, node.data <= last_printed * 前进条件: last_printed = node.data checkBST(node.left), checkBST(node.right) */ public static int last_printed = Integer.MIN_VALUE; public static boolean checkBST(TreeNode node) { if (node == null) { return true; } if (!checkBST(node.left)) { return false; } if (node.data <= last_printed) { return false; } last_printed = node.data; if (!checkBST(node.right)) { return false; } return true; } /**二叉树满足的条件: the condition is that alI left nodes must be less than or equal to the current node, which must be less than all the right nodes. * * */ public static boolean checkBST2(TreeNode node) { return checkBST(node, Integer.MIN_VALUE, Integer.MAX_VALUE); } public static boolean checkBST(TreeNode node, int min, int max) { //边界条件 if (node == null) { return false; } if (node.data <= min || node.data > max) { return false; } if (!checkBST(node.left, min, node.data) || !checkBST(node.right, node.data, max)) { return false; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode o = new TreeNode(1); TreeNode t = new TreeNode(2); TreeNode th = new TreeNode(3); TreeNode four = new TreeNode(4); TreeNode five = new TreeNode(5); TreeNode six = new TreeNode(6); TreeNode seven = new TreeNode(7); TreeNode eight = new TreeNode(8); TreeNode nine = new TreeNode(9); /** * 1 * 2 3 * 4 5 6 7 * 8 9 */ o.left = t; o.right = th; t.right = five; t.left = four; th.left = six; th.right = seven; four.left = eight; four.right = nine; System.out.println(isBST(o)); System.out.println(checkBST(o)); System.out.println(checkBST2(o)); } }
0377961e9a534499bf072f655800c13920764eec
[ "Markdown", "Java" ]
14
Markdown
mulinsenpan/CrackingTheCodingInterview
cf53449606f7035794f2a93bd8d999300580aff9
5fc73146b57c9e93c5c8e68c0a6c4cf0a537e8d3
refs/heads/master
<repo_name>rafaelmvargas/web-front-end-final<file_sep>/src/js/modules/pokeDetails.mjs import { PokemonAPI } from "./api.mjs"; function showPokeDetails(pokemon) { var pokemonModal = document.querySelector(".pokemon-modal"); let getData = fetch(PokemonAPI + pokemon) .then((response) => response.json()) .then((monster) => { return console.log(`<div class="pokemon-details-image"><img src='${monster.sprites.other["official-artwork"].front_default}'>}</div> <div class="pokemon-details-name">${monster.name}</div> <div class="pokemon-details-type">${monster.types[0]}<div> </div> <div class="pokemon-details-abilities"></div>`); }); } export { showPokeDetails }; <file_sep>/src/pages/about.md --- title: About pageKind: about accessKey: a --- # Pokemon ![Pokemon](https://upload.wikimedia.org/wikipedia/commons/9/98/International_Pok%C3%A9mon_logo.svg) Pokémon,(an acronym for Pocket Monsters in Japan) is a Japanese media franchise managed by The Pokémon Company, a company founded by Nintendo, Game Freak, and Creatures. The franchise was created by <NAME> in 1995, and is centered on fictional creatures called "Pokémon". In Pokémon, humans, known as Pokémon Trainers, catch and train Pokémon to battle other Pokémon for sport. Games, shows and other works within the franchise are set in the Pokémon universe. The English slogan for the franchise is "Gotta Catch ‘Em All!". There are currently 898 Pokémon species. ## History The franchise began as Pocket Monsters: Red and Green (later released outside of Japan as Pokémon Red and Blue), a pair of video games for the original Game Boy handheld system that were developed by Game Freak and published by Nintendo in February 1996. It soon became a media mix franchise adapted into various different media. Pokémon has since become the highest-grossing media franchise of all time. The original video game series is the second-best-selling video game franchise (behind Nintendo's Mario franchise) with more than 380 million copies sold and one billion mobile downloads, and it spawned a anime television series that has become the most successful video game adaptation with over 20 seasons and 1,000 episodes in 169 countries. In addition, the Pokémon franchise includes the world's top-selling toy brand, the top-selling trading card game with over 34.1 billion cards sold, an anime film series, a live-action film (Detective Pikachu), books, manga comics, music, merchandise, and a temporary theme park. The franchise is also represented in other Nintendo media, such as the Super Smash Bros. series, where various Pokémon characters are playable. In November 2005, 4Kids Entertainment, which had managed the non-game related licensing of Pokémon, announced that it had agreed not to renew the Pokémon representation agreement. The Pokémon Company International oversees all Pokémon licensing outside Asia. In 2006, the franchise celebrated its tenth anniversary. In 2016, the Pokémon Company celebrated Pokémon's 20th anniversary by airing an ad during Super Bowl 50 in January and re-releasing the first Pokémon video games 1996 Game Boy games Pokémon Red, Green (only in Japan), and Blue, and the 1998 Game Boy Color game Pokémon Yellow for the Nintendo 3DS on February 26, 2016. The mobile augmented reality game Pokémon Go was released in July 2016. The first live-action film in the franchise, Pokémon Detective Pikachu, based on the 2018 Nintendo 3DS spin-off game Detective Pikachu, was released in 2019. The most recently released core series games, Pokémon Sword and Shield, that were released worldwide on the Nintendo Switch on November 15, 2019. ## Recently In celebration of its 25th anniversary in 2021, the upcoming core series games, Pokémon Brilliant Diamond and Shining Pearl will be released on November 19, 2021, and Pokémon Legends: Arceus on January 28, 2022, both for the Nintendo Switch. They are remakes and a "premake" of the 2006 Nintendo DS games Pokémon Diamond and Pearl, respectively. <file_sep>/src/js/modules/clickHandler.mjs import { showPokeDetails } from "./pokeDetails.mjs"; function clickHandler(event) { console.log(event.target); if (event.target.matches("#hamburger")) { showMenu(); } if (event.target.matches(".pokemon")) { showPokeDetails(event.target.id); } } function showMenu() { document.querySelector("body").classList.toggle("show-navigation-bar"); } export { clickHandler }; <file_sep>/notes.md <!-- Fetch the poke and make it an index page --> <!-- Once pokemon is clicked then show pokemon show page --> <file_sep>/src/pages/search.md --- tags: navigation title: Search pageKind: search date: 2021-07-03 accessKey: s --- <input class="searchBox" type="text"><file_sep>/src/js/modules/pokedex.mjs import { CatalogAPI, PokemonAPI } from "./api.mjs"; function setupPokeDex() { let pokeStore = window.localStorage; if (pokeStore.getItem("pokedex") === null || undefined) { console.log("Creating LocalStorage PokeDex"); fetch(CatalogAPI) .then((response) => { console.log(response); return response.json(); }) .then((data) => { return pokeStore.setItem("pokedex", JSON.stringify(data)); }); } else { console.log("pokedex found"); makePokemonTable(); } } function getPokedex() { let pokedex = JSON.parse(localStorage.getItem("pokedex")); return pokedex; } function makePokemonTable() { let pokedex = getPokedex(); var pokemonSummary = document.querySelector(".pokemonSummary"); let done = pokedex.results.map(function renderDivs(pokemon) { let info = fetchPokemonData(pokemon.name); return info; }); Promise.all(done).then((values) => { for (const [item, monster] of values.entries()) { pokemonSummary.innerHTML += `<div class="pokemonCard" id="${monster.name}"> <img src="${monster.imageUrl}" id="${monster.name}"> <div class="monster-name"><a href="#" class="pokemon" id="${monster.name}">${monster.name}<div> </a> </div>`; } }); } function fetchPokemonData(index) { let onePokemonAPI = PokemonAPI + `${index}/`; let returnCard = fetch(onePokemonAPI) .then((response) => response.json()) .then((data) => { let newData = { name: data.name, types: data.types, moves: data.moves, abilities: data.abilities, imageUrl: data.sprites.other["official-artwork"].front_default, }; return newData; }); return returnCard; } export { fetchPokemonData, getPokedex, setupPokeDex }; <file_sep>/src/js/modules/pokeGrid.mjs function applyPokeGrid() { const pokemonSummary = document.querySelector('.pokemonSummary') pokemonSummary.classList.toggle("pokeGrid"); } export { applyPokeGrid }; <file_sep>/README.md # Web Front End Final Using the pokemon api - [Pokemon API](https://pokeapi.co) - create a detail page that displays a summary view of a number of pokemon. Each pokemon in the summary page links to a detail view which displaysmore information about that pokemon. <file_sep>/src/pages/index.md --- title: Pokedex tags: navigation pageKind: home permalink: / accessKey: h date: 2021-07-01 ---
568163f249a47db46820d5002341331cc95833b6
[ "JavaScript", "Markdown" ]
9
JavaScript
rafaelmvargas/web-front-end-final
cf4945c778ec07048d6427229a9152a8503e4e7b
0c79efb4443486750b6b760c7cda6de7ee180a0c
refs/heads/master
<repo_name>simonnagel/VRED-actionBasedOnDistance<file_sep>/VRED-actionBasedOndistance.py ''' DISCLAIMER: --------------------------------- In any case, all binaries, configuration code, templates and snippets of this solution are of "work in progress" character. This also applies to GitHub "Release" versions. Neither <NAME>, nor Autodesk represents that these samples are reliable, accurate, complete, or otherwise valid. Accordingly, those configuration samples are provided ?as is? with no warranty of any kind and you use the applications at your own risk. ''' import math timer = vrTimer() timer.connect("actionBasedOnDistance()") timer.setActive(1) sphere = findNode("Sphere") goal = findNode("Goal") def actionBasedOnDistance(): spherePos = sphere.getTranslation() goalPos = goal.getTranslation() distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(spherePos, goalPos)])) #print distance if distance >500: selectVariantSet("Green") elif distance <500 and distance>250: selectVariantSet("Yellow") else: selectVariantSet("Red") <file_sep>/readme.md # Vred-actionBasedOnDistance ### vrTimer-actionBasedOnDistance: Simple Example on how create action based on distance between objects. In this scenario a variant is executed if certain distance values are reached ![](VRED-actionBasedOndistance.gif)
84efbf1a14cc7d249861c6dbb143f082e71a9bbd
[ "Markdown", "Python" ]
2
Python
simonnagel/VRED-actionBasedOnDistance
e1f692ec8a96638823250b4ed967da596c1577fb
2d2a0113aa7fd7a35e63469e64dfbb8efbad079b
refs/heads/main
<repo_name>Food-Ordering-Application/driver-android<file_sep>/app/src/main/java/com/foa/driver/adapter/OrderItemListAdapter.java package com.foa.driver.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.foa.driver.R; import com.foa.driver.model.DriverTransaction; import com.foa.driver.model.OrderItem; import com.foa.driver.model.enums.TransactionType; import com.foa.driver.util.Helper; import java.util.ArrayList; import java.util.List; public class OrderItemListAdapter extends RecyclerView.Adapter<OrderItemListAdapter.ViewHolder> { private Context context; private List<OrderItem> orderItemList; public OrderItemListAdapter(Context context, List<OrderItem> orderItemList) { this.context = context; this.orderItemList = orderItemList; } public void setOrderItems(List<OrderItem> orderItemList){ this.orderItemList = orderItemList; notifyDataSetChanged(); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.order_items_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { OrderItem orderItem = orderItemList.get(position); holder.menuItemNameTextView.setText(orderItem.getMenuItemName()); holder.quantityTextView.setText(String.valueOf(orderItem.getQuantity())); holder.subtotalTextView.setText(Helper.formatMoney(orderItem.getSubTotal())); final StringBuilder toppingNamesBuilder = new StringBuilder(); orderItem.getOrderItemToppings().forEach(item-> toppingNamesBuilder.append(item.getName()).append("\n")); holder.toppingListTextView.setText(toppingNamesBuilder.toString().trim()); holder.itemView.setTag(orderItem); } @Override public int getItemCount() { return orderItemList.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView menuItemNameTextView; TextView toppingListTextView; TextView quantityTextView; TextView subtotalTextView; public ViewHolder(@NonNull View itemView) { super(itemView); menuItemNameTextView = itemView.findViewById(R.id.menuItemNameTextView); toppingListTextView = itemView.findViewById(R.id.toppingItemListTextView); quantityTextView = itemView.findViewById(R.id.quantityTextView); subtotalTextView = itemView.findViewById(R.id.subTotalTextView); } } } <file_sep>/app/src/main/java/com/foa/driver/network/response/AccountWalletData.java package com.foa.driver.network.response; import com.foa.driver.model.AccountWallet; import com.google.gson.annotations.SerializedName; public class AccountWalletData { @SerializedName( "accountWallet" ) private AccountWallet accountWallet; public AccountWallet getAccountWallet() { return accountWallet; } public void setAccountWallet(AccountWallet accountWallet) { this.accountWallet = accountWallet; } }<file_sep>/app/src/main/java/com/foa/driver/fragment/OrderListFragment.java package com.foa.driver.fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.airbnb.lottie.LottieAnimationView; import com.foa.driver.R; import com.foa.driver.adapter.FoldingCellListAdapter; import com.foa.driver.api.OrderService; import com.foa.driver.entity.Item; import com.foa.driver.model.Order; import com.foa.driver.model.enums.DeliveryStatus; import com.foa.driver.model.enums.OrderStatusQuery; import com.foa.driver.network.IDataResultCallback; import com.foa.driver.session.LoginSession; import com.ramotion.foldingcell.FoldingCell; import java.util.ArrayList; import java.util.List; public class OrderListFragment extends Fragment { private View root; private ListView theListView; private FoldingCellListAdapter adapter; private LottieAnimationView driverLoadingView; private OrderStatusQuery type; private TextView emptyListTextView; private boolean isFirst=false; public OrderListFragment(OrderStatusQuery type){ this.type = type; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_order_list, container, false); theListView = root.findViewById(R.id.mainListView); driverLoadingView = root.findViewById(R.id.driverLoadingView); emptyListTextView = root.findViewById(R.id.emptyListTextView); emptyListTextView.setVisibility(View.GONE); return root; } @Override public void onResume() { super.onResume(); if (!isFirst){ driverLoadingView.setVisibility(View.VISIBLE); OrderService.getAllOrder(LoginSession.getInstance().getDriver().getId(), type.name(), 1,25, (success, data) -> { if (success){ if (data.size()==0) emptyListTextView.setVisibility(View.VISIBLE); driverLoadingView.setVisibility(View.GONE); if (type== OrderStatusQuery.ACTIVE && data.size()>0){ List<Order> list = new ArrayList<>(); list.add(data.get(0)); adapter = new FoldingCellListAdapter(getActivity(),type); adapter.setOrders(list); theListView.setAdapter(adapter); try { Thread.sleep(200); adapter.registerToggle(0); } catch (InterruptedException e) { e.printStackTrace(); } }else{ adapter = new FoldingCellListAdapter(getActivity(),type); adapter.setOrders(data); theListView.setAdapter(adapter); theListView.setOnItemClickListener((adapterView, view, pos, l) -> { ((FoldingCell) view).toggle(false); adapter.registerToggle(pos); }); } isFirst =true; }else{ emptyListTextView.setVisibility(View.VISIBLE); driverLoadingView.setVisibility(View.GONE); } }); } } @Override public void onPause() { super.onPause(); if (adapter!=null) adapter.clearUnfoldedIndexes(); } }<file_sep>/app/src/main/java/com/foa/driver/model/enums/OrderStatusQuery.java package com.foa.driver.model.enums; public enum OrderStatusQuery { ACTIVE, COMPLETED } <file_sep>/app/src/main/java/com/foa/driver/session/DriverModeSession.java package com.foa.driver.session; import com.foa.driver.model.enums.DeliveryStatus; public class DriverModeSession { private static DeliveryStatus deliveryStatus = DeliveryStatus.DRAFT; public DriverModeSession() { } public static DeliveryStatus getInstance(){ return deliveryStatus; } public static void setInstance(DeliveryStatus isDriving){ DriverModeSession.deliveryStatus = isDriving; } public static void clearInstance(){ DriverModeSession.deliveryStatus = DeliveryStatus.DRAFT; } } <file_sep>/app/build.gradle plugins { id 'com.android.application' id 'com.google.gms.google-services' } android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.foa.driver" minSdkVersion 24 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } lintOptions { checkReleaseBuilds false // Or, if you prefer, you can continue to check for errors in release builds, // but continue the build even when errors are found: abortOnError false } } dependencies { implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation 'androidx.navigation:navigation-fragment:2.3.5' implementation 'androidx.navigation:navigation-ui:2.3.5' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1' implementation 'com.ramotion.foldingcell:folding-cell:1.2.3' implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.github.PhilJay:MPAndroidChart:v3.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'androidx.annotation:annotation:1.1.0' implementation'com.squareup.okhttp3:logging-interceptor:4.9.1' implementation'com.github.stfalcon:swipeable-button:0.1.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:9.6.1' implementation 'com.mapbox.mapboxsdk:mapbox-sdk-services:5.8.0' implementation platform('com.google.firebase:firebase-bom:27.1.0') implementation 'com.google.firebase:firebase-analytics' implementation 'com.google.firebase:firebase-core:17.4.4' implementation 'com.google.firebase:firebase-messaging:20.2.3' implementation 'com.pusher:push-notifications-android:1.6.2' implementation 'com.pusher:pusher-java-client:2.2.6' implementation 'de.hdodenhof:circleimageview:3.1.0' implementation 'com.paypal.checkout:android-sdk:0.2.0' implementation 'com.google.android.gms:play-services-location:16.0.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.42.6' implementation 'com.mapbox.navigator:mapbox-navigation-native:7.0.0' implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3' implementation "com.airbnb.android:lottie:3.4.0" implementation 'com.pubnub:pubnub-gson:4.+' implementation files('libs/AndroidEasingFunctions-1.0.0.jar') implementation files('libs/AndroidViewAnimations-1.1.3.jar') implementation files('libs/btsdk.jar') implementation files('libs/NineOldAndroid-2.4.0.jar') }<file_sep>/app/src/main/java/com/foa/driver/network/response/DepositData.java package com.foa.driver.network.response; import com.google.gson.annotations.SerializedName; public class DepositData { @SerializedName( "mainBalance" ) long mainBalance; public long getMainBalance() { return mainBalance; } public void setMainBalance(long mainBalance) { this.mainBalance = mainBalance; } }<file_sep>/app/src/main/java/com/foa/driver/model/Driver.java package com.foa.driver.model; import com.google.gson.annotations.SerializedName; import java.util.Date; public class Driver { @SerializedName("id") private String id; @SerializedName("phoneNumber") private String phoneNumber; @SerializedName("email") private String email; @SerializedName("name") private String name; @SerializedName("city") private String city; @SerializedName("dateOfBirth") private Date dateOfBirth; @SerializedName("IDNumber") private String IDNumber; @SerializedName("licensePlate") private String licensePlate; @SerializedName("avatar") private String avatar; @SerializedName("identityCardImageUrl") private String identityCardImageUrl; @SerializedName("driverLicenseImageUrl") private String driverLicenseImageUrl; @SerializedName("vehicleRegistrationCertificateImageUrl") private String vehicleRegistrationCertificateImageUrl; @SerializedName("isVerified") private boolean isVerified; @SerializedName("isBanned") private boolean isBanned; @SerializedName("beforeUpdatePassword") private String beforeUpdatePassword; public Driver(String id, String phoneNumber, String email, String name, String city, Date dateOfBirth, String IDNumber, String licensePlate, String avatar, String identityCardImageUrl, String driverLicenseImageUrl, String vehicleRegistrationCertificateImageUrl, boolean isVerified, boolean isBanned, String beforeUpdatePassword) { this.id = id; this.phoneNumber = phoneNumber; this.email = email; this.name = name; this.city = city; this.dateOfBirth = dateOfBirth; this.IDNumber = IDNumber; this.licensePlate = licensePlate; this.avatar = avatar; this.identityCardImageUrl = identityCardImageUrl; this.driverLicenseImageUrl = driverLicenseImageUrl; this.vehicleRegistrationCertificateImageUrl = vehicleRegistrationCertificateImageUrl; this.isVerified = isVerified; this.isBanned = isBanned; this.beforeUpdatePassword = beforeUpdatePassword; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getIDNumber() { return IDNumber; } public void setIDNumber(String IDNumber) { this.IDNumber = IDNumber; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getIdentityCardImageUrl() { return identityCardImageUrl; } public void setIdentityCardImageUrl(String identityCardImageUrl) { this.identityCardImageUrl = identityCardImageUrl; } public String getDriverLicenseImageUrl() { return driverLicenseImageUrl; } public void setDriverLicenseImageUrl(String driverLicenseImageUrl) { this.driverLicenseImageUrl = driverLicenseImageUrl; } public String getVehicleRegistrationCertificateImageUrl() { return vehicleRegistrationCertificateImageUrl; } public void setVehicleRegistrationCertificateImageUrl(String vehicleRegistrationCertificateImageUrl) { this.vehicleRegistrationCertificateImageUrl = vehicleRegistrationCertificateImageUrl; } public boolean isVerified() { return isVerified; } public void setVerified(boolean verified) { isVerified = verified; } public boolean isBanned() { return isBanned; } public void setBanned(boolean banned) { isBanned = banned; } public String getBeforeUpdatePassword() { return beforeUpdatePassword; } public void setBeforeUpdatePassword(String beforeUpdatePassword) { this.beforeUpdatePassword = <PASSWORD>UpdatePassword; } } <file_sep>/app/src/main/java/com/foa/driver/service/NotificationsMessagingService.java package com.foa.driver.service; import android.util.Log; import com.google.firebase.messaging.RemoteMessage; import com.pusher.pushnotifications.fcm.MessagingService; public class NotificationsMessagingService extends MessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.e("FCM","Receive message!!!"); } }<file_sep>/app/src/main/java/com/foa/driver/network/body/LocationBody.java package com.foa.driver.network.body; import com.google.gson.annotations.SerializedName; public class LocationBody { @SerializedName("latitude") private double latitude; @SerializedName("longitude") private double longitude; public LocationBody(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } } <file_sep>/app/src/main/java/com/foa/driver/api/UserService.java package com.foa.driver.api; import android.location.Location; import android.util.Log; import com.foa.driver.model.AccountWallet; import com.foa.driver.model.DriverTransaction; import com.foa.driver.model.StatisticItem; import com.foa.driver.model.enums.TransactionStatus; import com.foa.driver.model.enums.TransactionType; import com.foa.driver.network.IDataResultCallback; import com.foa.driver.network.IResultCallback; import com.foa.driver.network.RetrofitClient; import com.foa.driver.network.body.ApproveDepositBody; import com.foa.driver.network.body.CreateDepositBody; import com.foa.driver.network.body.LocationBody; import com.foa.driver.network.body.UpdateActiveBody; import com.foa.driver.network.body.WithdrawMoneyBody; import com.foa.driver.network.response.AccountWalletData; import com.foa.driver.network.response.ActiveData; import com.foa.driver.network.response.DepositData; import com.foa.driver.network.response.CreateDepositData; import com.foa.driver.network.response.LoginData; import com.foa.driver.network.response.ResponseAdapter; import com.foa.driver.network.response.StatisticListData; import com.foa.driver.network.response.TransactionListData; import com.foa.driver.session.LoginSession; import com.foa.driver.util.Constants; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class UserService { public static void createDepositMoneyToMainWallet(long moneyToDeposit, IDataResultCallback<String> resultCallback) { String driverId = LoginSession.getInstance().getDriver().getId(); Call<ResponseAdapter<CreateDepositData>> responseCall = RetrofitClient.getInstance().getAppService() .createDepositMoneyToMainWallet(driverId,new CreateDepositBody(moneyToDeposit)); responseCall.enqueue(new Callback<ResponseAdapter<CreateDepositData>>() { @Override public void onResponse(Call<ResponseAdapter<CreateDepositData>> call, Response<ResponseAdapter<CreateDepositData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<CreateDepositData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData().getPaypalOrderId()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<CreateDepositData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void approveDepositMoneyToMainWallet(String paypalOrderId, IDataResultCallback<DepositData> resultCallback) { String driverId = LoginSession.getInstance().getDriver().getId(); Call<ResponseAdapter<DepositData>> responseCall = RetrofitClient.getInstance().getAppService() .approveDepositMoneyToMainWallet(driverId,new ApproveDepositBody(paypalOrderId)); responseCall.enqueue(new Callback<ResponseAdapter<DepositData>>() { @Override public void onResponse(Call<ResponseAdapter<DepositData>> call, Response<ResponseAdapter<DepositData>> response) { Log.e("PAYPAL_DEPOSIT","api status"+ response.code()); if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<DepositData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<DepositData>> call, Throwable t) { Log.e("PAYPAL_DEPOSIT","api fail"); resultCallback.onSuccess(false,null); } }); } public static void withdrawMoneyToPayPalAccount(String driverId, long moneyToWithdraw, IResultCallback resultCallback) { Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .withdrawMoneyToPayPalAccount(driverId,new WithdrawMoneyBody(moneyToWithdraw)); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } public static void getAccountWallet(String driverId, IDataResultCallback<AccountWallet> resultCallback) { Call<ResponseAdapter<AccountWalletData>> responseCall = RetrofitClient.getInstance().getAppService() .getAccountWallet(driverId); responseCall.enqueue(new Callback<ResponseAdapter<AccountWalletData>>() { @Override public void onResponse(Call<ResponseAdapter<AccountWalletData>> call, Response<ResponseAdapter<AccountWalletData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<AccountWalletData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData().getAccountWallet()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<AccountWalletData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void getTransactionHistory(String driverId, IDataResultCallback<List<DriverTransaction>> resultCallback) { Call<ResponseAdapter<TransactionListData>> responseCall = RetrofitClient.getInstance().getAppService() .getTransactionHistory(driverId, TransactionType.ALL.name(),1,5,TransactionStatus.ALL.name()); responseCall.enqueue(new Callback<ResponseAdapter<TransactionListData>>() { @Override public void onResponse(Call<ResponseAdapter<TransactionListData>> call, Response<ResponseAdapter<TransactionListData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<TransactionListData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData().getDriverTransactions()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<TransactionListData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void getStatisticMonthly(IDataResultCallback<List<StatisticItem>> resultCallback) { String driverId = LoginSession.getInstance().getDriver().getId(); Call<ResponseAdapter<StatisticListData>> responseCall = RetrofitClient.getInstance().getAppService() .getStatisticMonthly(driverId); responseCall.enqueue(new Callback<ResponseAdapter<StatisticListData>>() { @Override public void onResponse(Call<ResponseAdapter<StatisticListData>> call, Response<ResponseAdapter<StatisticListData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<StatisticListData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData().getStatisticItemList()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<StatisticListData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void getStatisticWeekly(IDataResultCallback<List<StatisticItem>> resultCallback) { String driverId = LoginSession.getInstance().getDriver().getId(); Call<ResponseAdapter<StatisticListData>> responseCall = RetrofitClient.getInstance().getAppService() .getStatisticWeekly(driverId); responseCall.enqueue(new Callback<ResponseAdapter<StatisticListData>>() { @Override public void onResponse(Call<ResponseAdapter<StatisticListData>> call, Response<ResponseAdapter<StatisticListData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<StatisticListData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData().getStatisticItemList()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<StatisticListData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void getActive( IDataResultCallback<ActiveData> resultCallback) { Call<ResponseAdapter<ActiveData>> responseCall = RetrofitClient.getInstance().getAppService() .getActive(); responseCall.enqueue(new Callback<ResponseAdapter<ActiveData>>() { @Override public void onResponse(Call<ResponseAdapter<ActiveData>> call, Response<ResponseAdapter<ActiveData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<ActiveData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true,res.getData()); } else { resultCallback.onSuccess(false,null); } } else { resultCallback.onSuccess(false,null); } } @Override public void onFailure(Call<ResponseAdapter<ActiveData>> call, Throwable t) { resultCallback.onSuccess(false,null); } }); } public static void updateIsActive(boolean isActive, Location location, IResultCallback resultCallback) { UpdateActiveBody body; if (isActive && location!=null){ body = new UpdateActiveBody(true,location.getLatitude(),location.getLongitude()); }else{ body = new UpdateActiveBody(false); } Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .updateIsActive(body); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } public static void updateLocation(Location location, IResultCallback resultCallback) { Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .updateLocation(new LocationBody(location.getLatitude(),location.getLongitude())); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } } <file_sep>/app/src/main/java/com/foa/driver/model/enums/InvoiceStatus.java package com.foa.driver.model.enums; public enum InvoiceStatus { PAID, UNPAID, REFUNDED , CANCELLED, } <file_sep>/app/src/main/java/com/foa/driver/model/enums/OrderStatus.java package com.foa.driver.model.enums; import com.google.gson.annotations.SerializedName; public enum OrderStatus { @SerializedName("DRAFT") DRAFT, @SerializedName("ORDERED") ORDERED, @SerializedName("COMPLETED") COMPLETED, @SerializedName("CONFIRMED") CONFIRMED, @SerializedName("CANCELLED") CANCELLED }<file_sep>/app/src/main/java/com/foa/driver/model/PayInTransaction.java package com.foa.driver.model; import com.foa.driver.model.enums.TransactionStatus; import com.google.gson.annotations.SerializedName; public class PayInTransaction { @SerializedName("id") private String id; @SerializedName("status") private TransactionStatus status; @SerializedName("captureId") private String captureId; @SerializedName("paypalOrderId") private String paypalOrderId; @SerializedName("createdAt") private String createdAt; @SerializedName("updatedAt") private String updatedAt; public String getId() { return id; } public void setId(String id) { this.id = id; } public TransactionStatus getStatus() { return status; } public void setStatus(TransactionStatus status) { this.status = status; } public String getCaptureId() { return captureId; } public void setCaptureId(String captureId) { this.captureId = captureId; } public String getPaypalOrderId() { return paypalOrderId; } public void setPaypalOrderId(String paypalOrderId) { this.paypalOrderId = paypalOrderId; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } } <file_sep>/app/src/main/java/com/foa/driver/model/Invoice.java package com.foa.driver.model; import com.foa.driver.model.enums.InvoiceStatus; import com.google.gson.annotations.SerializedName; public class Invoice { @SerializedName("status") private InvoiceStatus status; @SerializedName("payment") private Payment payment; } <file_sep>/app/src/main/java/com/foa/driver/network/response/StatisticListData.java package com.foa.driver.network.response; import com.foa.driver.model.DriverTransaction; import com.foa.driver.model.StatisticItem; import com.google.gson.annotations.SerializedName; import java.util.List; public class StatisticListData { @SerializedName("statistic") List<StatisticItem> statisticItemList; public List<StatisticItem> getStatisticItemList() { return statisticItemList; } public void setStatisticItemList(List<StatisticItem> statisticItemList) { this.statisticItemList = statisticItemList; } } <file_sep>/app/src/main/java/com/foa/driver/util/Constants.java package com.foa.driver.util; public class Constants { //HTTP RES CODE public static final int STATUS_CODE_SUCCESS = 200; public static final int STATUS_CODE_CREATED = 201; public static final int STATUS_CODE_UNAUTHORIZED = 401; public static final int STATUS_CODE_FORBIDDEN = 403; public static final int STATUS_CODE_NOT_FOUND = 404; //PREFERENCE_SHARE public static final String LAST_LATITUDE ="last_latitude"; public static final String LAST_LONGITUDE ="last_longitude"; } <file_sep>/app/src/main/java/com/foa/driver/service/LocationService.java package com.foa.driver.service; import android.Manifest; import android.app.ActivityManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.util.TimingLogger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; import androidx.core.app.NotificationCompat; import com.foa.driver.api.UserService; import com.foa.driver.config.Config; import com.foa.driver.network.IResultCallback; import com.foa.driver.network.body.DriverLocationBody; import com.foa.driver.session.LoginSession; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.gson.JsonObject; import com.pubnub.api.PNConfiguration; import com.pubnub.api.PubNub; import com.pubnub.api.callbacks.PNCallback; import com.pubnub.api.models.consumer.PNPublishResult; import com.pubnub.api.models.consumer.PNStatus; public class LocationService extends Service { private LocationManager mLocationManager = null; private TimingLogger timings; private FusedLocationProviderClient client; private final String TAG = "LOCATION_SERVICE"; private boolean started = false; private Handler handler = new Handler(); private Location lastLocation; private PubNub pubNub; private final int LOCATION_REFRESH_TIME = 10000; private final int LOCATION_REFRESH_DISTANCE = 0; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } client = LocationServices.getFusedLocationProviderClient(this); client.getLastLocation() .addOnSuccessListener(location -> { if (location != null) { lastLocation = location; Log.e("Service init last location", location.getLatitude() + "," + location.getLongitude()); } }); timings = new TimingLogger("Update_Location", "Initialization"); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) startMyOwnForeground(); else startForeground(1, new Notification()); } @RequiresApi(Build.VERSION_CODES.O) private void startMyOwnForeground() { String NOTIFICATION_CHANNEL_ID = "example.permanence"; String channelName = "Background Service"; NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE); chan.setLightColor(Color.BLUE); chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle("Ứng dụng Driver đang thu thập vị trí") .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { }else{ mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, new ServiceLocationListener()); initPubNub(); startUpdateLocation(); } return START_STICKY; } private Runnable runnable = () -> { updateLocationToServer(); if(started) { startUpdateLocation(); } }; public void stopUpdateLocation() { pubNub.unsubscribeAll(); started = false; handler.removeCallbacks(runnable); } public void startUpdateLocation() { started = true; handler.postDelayed(runnable, 15000); } private void updateLocationToServer() { JsonObject entryUpdate = new JsonObject(); entryUpdate.addProperty("message", "location-update"); JsonObject entryDataUpdate = new JsonObject(); entryDataUpdate.addProperty("driverId",LoginSession.getInstance().getDriver().getId()); entryDataUpdate.addProperty("latitude",lastLocation.getLatitude()); entryDataUpdate.addProperty("longitude",lastLocation.getLongitude()); entryUpdate.add("payload",entryDataUpdate); pubNub.publish().channel(Config.PUBNUB_CHANNEL_NAME).message(entryUpdate) .async((result, status) -> { if (status.isError()) { status.getErrorData().getThrowable().printStackTrace(); } else { Log.e("[PUBLISH: sent]", "timetoken: " + result.getTimetoken()); } }); // UserService.updateLocation(lastLocation, success -> { // if (success) // Log.e("service", "call api:"+ lastLocation.getLatitude()+";"+lastLocation.getLongitude()); // }); } private void initPubNub(){ PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setPublishKey(Config.PUBNUB_PUBLISH_KEY); pnConfiguration.setSubscribeKey(Config.PUBNUB_SUBSCRIBE_KEY); pnConfiguration.setUuid(LoginSession.getInstance().getDriver().getId()); pubNub = new PubNub(pnConfiguration); } @Override public void onDestroy() { super.onDestroy(); stopUpdateLocation(); Log.e("locaton","service destroy"); } private class ServiceLocationListener implements LocationListener{ @Override public void onLocationChanged(@NonNull Location location) { lastLocation = location; } @Override public void onProviderEnabled(@NonNull String provider) { } @Override public void onProviderDisabled(@NonNull String provider) { } } } <file_sep>/app/src/main/java/com/foa/driver/adapter/TransactionListAdapter.java package com.foa.driver.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.foa.driver.R; import com.foa.driver.model.DriverTransaction; import com.foa.driver.model.enums.TransactionType; import com.foa.driver.util.Helper; import java.text.ParseException; import java.time.LocalDateTime; import java.util.List; public class TransactionListAdapter extends RecyclerView.Adapter<TransactionListAdapter.ViewHolder> { private Context context; private List<DriverTransaction> transactionList; public TransactionListAdapter(Context context, List<DriverTransaction> transactionList) { this.context = context; this.transactionList = transactionList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.transaction_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { DriverTransaction transaction = transactionList.get(position); //set data if (transaction.getType()== TransactionType.PAYIN){ holder.transactionIcon.setImageDrawable(context.getDrawable(R.drawable.ic_money_green)); holder.transactionSign.setText("+"); holder.transactionType.setText("Nạp tiền"); }else{ holder.transactionIcon.setImageDrawable(context.getDrawable(R.drawable.ic_money_red)); holder.transactionSign.setText("-"); holder.transactionType.setText("Rút tiền"); } holder.transactionAmount.setText(Helper.formatMoney(transaction.getAmount())); holder.transactionTime.setText(Helper.getTimeFormUTC(transaction.getCreatedAt()).getFull()); holder.itemView.setTag(transaction); } @Override public int getItemCount() { return transactionList.size(); } class ViewHolder extends RecyclerView.ViewHolder { ImageView transactionIcon; TextView transactionAmount; TextView transactionType; TextView transactionTime; TextView transactionSign; public ViewHolder(@NonNull View itemView) { super(itemView); transactionIcon = itemView.findViewById(R.id.transactionIcon); transactionAmount = itemView.findViewById(R.id.transactionAmount); transactionType = itemView.findViewById(R.id.transactionType); transactionTime = itemView.findViewById(R.id.transactionTime); transactionSign = itemView.findViewById(R.id.transactionSign); } } } <file_sep>/app/src/main/java/com/foa/driver/api/OrderService.java package com.foa.driver.api; import com.foa.driver.model.Order; import com.foa.driver.network.IDataResultCallback; import com.foa.driver.network.IResultCallback; import com.foa.driver.network.RetrofitClient; import com.foa.driver.network.body.ApproveDepositBody; import com.foa.driver.network.body.CreateDepositBody; import com.foa.driver.network.body.WithdrawMoneyBody; import com.foa.driver.network.response.CreateDepositData; import com.foa.driver.network.response.OrderData; import com.foa.driver.network.response.OrderListData; import com.foa.driver.network.response.ResponseAdapter; import com.foa.driver.util.Constants; import com.foa.driver.util.Helper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class OrderService { public static void getOrderById(String orderId, IDataResultCallback<Order> resultCallback) { Call<ResponseAdapter<OrderData>> responseCall = RetrofitClient.getInstance().getAppService() .getOrderById(orderId); responseCall.enqueue(new Callback<ResponseAdapter<OrderData>>() { @Override public void onResponse(Call<ResponseAdapter<OrderData>> call, Response<ResponseAdapter<OrderData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<OrderData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true, res.getData().getOrder()); } else { resultCallback.onSuccess(false, null); } } else { resultCallback.onSuccess(false, null); } } @Override public void onFailure(Call<ResponseAdapter<OrderData>> call, Throwable t) { } }); } public static void getAllOrder(String driverId, String status,int page, int size, IDataResultCallback<List<Order>> resultCallback) { GregorianCalendar calendar = new GregorianCalendar(); String startDate = Helper.dateSQLiteFormat.format(calendar.getTime()); calendar.add(Calendar.DATE,1); String endDate = Helper.dateSQLiteFormat.format(calendar.getTime()); getAllOrder(driverId, status, page, size,startDate,endDate, resultCallback); } public static void getAllOrder(String driverId, String status,int page, int size,String startDate, String endDate, IDataResultCallback<List<Order>> resultCallback) { Call<ResponseAdapter<OrderListData>> responseCall = RetrofitClient.getInstance().getAppService() .getAllOrder(driverId, status, page, size,startDate,endDate); responseCall.enqueue(new Callback<ResponseAdapter<OrderListData>>() { @Override public void onResponse(Call<ResponseAdapter<OrderListData>> call, Response<ResponseAdapter<OrderListData>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<OrderListData> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true, res.getData().getOrders()); } else { resultCallback.onSuccess(false, null); } } else { resultCallback.onSuccess(false, null); } } @Override public void onFailure(Call<ResponseAdapter<OrderListData>> call, Throwable t) { resultCallback.onSuccess(false, null); } }); } public static void acceptOrder(String orderId, IResultCallback resultCallback) { Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .acceptOrder(orderId); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } public static void pickupOrder(String orderId, IResultCallback resultCallback) { Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .pickupOrder(orderId); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } public static void completeOrder(String orderId, IResultCallback resultCallback) { Call<ResponseAdapter<String>> responseCall = RetrofitClient.getInstance().getAppService() .completeOrder(orderId); responseCall.enqueue(new Callback<ResponseAdapter<String>>() { @Override public void onResponse(Call<ResponseAdapter<String>> call, Response<ResponseAdapter<String>> response) { if (response.code() == Constants.STATUS_CODE_SUCCESS) { ResponseAdapter<String> res = response.body(); assert res != null; if (res.getStatus() == Constants.STATUS_CODE_SUCCESS) { resultCallback.onSuccess(true); } else { resultCallback.onSuccess(false); } } else { resultCallback.onSuccess(false); } } @Override public void onFailure(Call<ResponseAdapter<String>> call, Throwable t) { resultCallback.onSuccess(false); } }); } } <file_sep>/app/src/main/java/com/foa/driver/caching/StatisticMonthlyCatching.java package com.foa.driver.caching; import com.foa.driver.model.Order; import com.foa.driver.model.StatisticItem; import java.util.List; public class StatisticMonthlyCatching { private static List<StatisticItem> statisticItemList = null; public static List<StatisticItem> getOrderCatching(){ return statisticItemList; } public static void setInstance(List<StatisticItem> statisticItems){ statisticItemList = statisticItems; } public static void clearInstance(){ statisticItemList = null; } } <file_sep>/app/src/main/java/com/foa/driver/adapter/RevenueListAdapter.java package com.foa.driver.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.foa.driver.R; import com.foa.driver.entity.StatisticItem; import com.foa.driver.model.DriverTransaction; import com.foa.driver.model.enums.StatisticType; import com.foa.driver.model.enums.TransactionType; import com.foa.driver.util.Helper; import java.util.List; public class RevenueListAdapter extends RecyclerView.Adapter<RevenueListAdapter.ViewHolder> { private Context context; private List<StatisticItem> revenueList; private StatisticType type; public RevenueListAdapter(Context context, List<StatisticItem> revenueList) { this.context = context; this.revenueList = revenueList; } public RevenueListAdapter(Context context) { this.context = context; } public void setData(List<StatisticItem> revenueList, StatisticType type){ this.revenueList = revenueList; this.type = type; notifyDataSetChanged(); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.revenue_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { StatisticItem item = revenueList.get(position); holder.revenueTime.setText(String.valueOf(item.getDay())); holder.revenueAmount.setText(Helper.formatMoney((long)item.getValue())); switch (type){ case DAY: holder.dayTextView.setText(""); break; case WEEK: holder.dayTextView.setText("Thứ "); break; case MONTH: holder.dayTextView.setText("Ngày "); break; } holder.itemView.setTag(item); } @Override public int getItemCount() { return revenueList.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView revenueAmount; TextView revenueTime; TextView dayTextView; public ViewHolder(@NonNull View itemView) { super(itemView); revenueAmount = itemView.findViewById(R.id.revenueAmount); revenueTime = itemView.findViewById(R.id.revenueTime); dayTextView = itemView.findViewById(R.id.dayTextView); } } } <file_sep>/app/src/main/java/com/foa/driver/fragment/StatisticFragment.java package com.foa.driver.fragment; import android.annotation.SuppressLint; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.airbnb.lottie.LottieAnimationView; import com.foa.driver.R; import com.foa.driver.adapter.RevenueListAdapter; import com.foa.driver.api.UserService; import com.foa.driver.caching.StatisticMonthlyCatching; import com.foa.driver.caching.StatisticWeeklyCatching; import com.foa.driver.model.StatisticItem; import com.foa.driver.model.enums.StatisticType; import com.foa.driver.network.IResultCallback; import com.foa.driver.util.Helper; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.formatter.IValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ViewPortHandler; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; public class StatisticFragment extends Fragment { private View root; private BarChart dayOfWeekChart; private BarChart dayOfMonthChart; private LottieAnimationView driverLoadingView; private RevenueListAdapter adapter; private LinearLayout detailDayStatisticCart; private TextView dayDetailTextView; private TextView numberOrdersTextView; private TextView totalShippingFee; private TextView commissionTextView; private TextView incomeTextView; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_statistic, container, false); dayOfWeekChart = root.findViewById(R.id.dayOfWeekChart); dayOfMonthChart = root.findViewById(R.id.dayOfMonthChart); driverLoadingView = root.findViewById(R.id.driverLoadingView); detailDayStatisticCart = root.findViewById(R.id.detailDayStatisticCart); dayDetailTextView = root.findViewById(R.id.dayTextView); numberOrdersTextView = root.findViewById(R.id.numOrderFinishedTextView); totalShippingFee = root.findViewById(R.id.totalShippingFeeTextView); commissionTextView = root.findViewById(R.id.commissionTextView); incomeTextView = root.findViewById(R.id.incomeTextView); initDayOfWeekChart(); initDayOfMonthChart(); initTimeRadioGroup(); return root; } @Override public void onResume() { super.onResume(); loadData(R.id.todayRadioButton); } @Override public void onDestroy() { super.onDestroy(); StatisticMonthlyCatching.clearInstance(); StatisticWeeklyCatching.clearInstance(); } private void loadDetailStatistic(int index, boolean isMonth, StatisticItem item){ dayDetailTextView.setText(getCurrentDateByIndex(index,isMonth)); numberOrdersTextView.setText(String.valueOf(item.getNumOrderFinished())); totalShippingFee.setText(Helper.formatMoney(item.getTotalShippingFee())); commissionTextView.setText(Helper.formatMoney(item.getCommission())); incomeTextView.setText(Helper.formatMoney(item.getIncome())); detailDayStatisticCart.setVisibility(View.VISIBLE); } @SuppressLint("NonConstantResourceId") private void initTimeRadioGroup(){ RadioGroup radioGroup = root.findViewById(R.id.timeRadioGroup); radioGroup.setOnCheckedChangeListener((rd, i) -> { detailDayStatisticCart.setVisibility(View.GONE); switch (rd.getCheckedRadioButtonId()){ case R.id.todayRadioButton: loadData(R.id.todayRadioButton); break; case R.id.thisWeekRadioButton: loadData(R.id.thisWeekRadioButton); break; case R.id.thisMonthRadioButton: loadData(R.id.thisMonthRadioButton); break; } }); } private void loadData(int radioButtonId){ List<StatisticItem> cachingList; switch (radioButtonId){ case R.id.todayRadioButton: driverLoadingView.setVisibility(View.GONE); cachingList =StatisticWeeklyCatching.getOrderCatching(); if (cachingList!=null){ dayOfWeekChart.setData(createBarEntry(StatisticWeeklyCatching.getOrderCatching())); int index = getCurrentDateIndexInWeek(); loadDetailStatistic(index,false,cachingList.get(index)); }else{ driverLoadingView.setVisibility(View.VISIBLE); detailDayStatisticCart.setVisibility(View.GONE); UserService.getStatisticWeekly((success,data) -> { if (success){ StatisticWeeklyCatching.setInstance(data); int index = getCurrentDateIndexInWeek(); loadDetailStatistic(index,false,data.get(index)); driverLoadingView.setVisibility(View.GONE); detailDayStatisticCart.setVisibility(View.VISIBLE); } }); } XAxis xAxis = dayOfWeekChart.getXAxis(); xAxis.setValueFormatter(new DateForFormatter()); dayOfWeekChart.setVisibility(View.GONE); dayOfMonthChart.setVisibility(View.GONE); break; case R.id.thisWeekRadioButton: driverLoadingView.setVisibility(View.GONE); dayOfMonthChart.setVisibility(View.GONE); if (StatisticWeeklyCatching.getOrderCatching()!=null){ dayOfWeekChart.setData(createBarEntry(StatisticWeeklyCatching.getOrderCatching())); dayOfMonthChart.setVisibleXRangeMaximum(7); dayOfWeekChart.setVisibility(View.VISIBLE); }else{ driverLoadingView.setVisibility(View.VISIBLE); UserService.getStatisticWeekly((success,data) -> { if (success){ dayOfWeekChart.setData(createBarEntry(data)); dayOfWeekChart.setVisibleXRangeMaximum(7); StatisticWeeklyCatching.setInstance(data); driverLoadingView.setVisibility(View.GONE); detailDayStatisticCart.setVisibility(View.VISIBLE); dayOfWeekChart.setVisibility(View.VISIBLE); } }); } break; case R.id.thisMonthRadioButton: driverLoadingView.setVisibility(View.GONE); if (StatisticMonthlyCatching.getOrderCatching()!=null){ dayOfMonthChart.setData(createBarEntry(StatisticMonthlyCatching.getOrderCatching())); dayOfMonthChart.setVisibleXRangeMaximum(10); dayOfMonthChart.moveViewToX(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); dayOfMonthChart.setVisibility(View.VISIBLE); }else{ driverLoadingView.setVisibility(View.VISIBLE); dayOfWeekChart.setVisibility(View.GONE); UserService.getStatisticMonthly((success,data) -> { if (success){ dayOfMonthChart.setData(createBarEntry(data)); dayOfMonthChart.setVisibleXRangeMaximum(10); StatisticMonthlyCatching.setInstance(data); driverLoadingView.setVisibility(View.GONE); detailDayStatisticCart.setVisibility(View.VISIBLE); dayOfMonthChart.setVisibility(View.VISIBLE); } }); } break; } } private BarData createBarEntry(List<StatisticItem> statisticItems){ List<BarEntry> entries = new ArrayList<>(); for (int i =0; i< statisticItems.size();i++) { entries.add(new BarEntry(i+1, statisticItems.get(i).getIncome())); } BarDataSet barDataSet = new BarDataSet(entries,"Thu nhập"); BarData barData = new BarData(barDataSet); barData.setValueFormatter(new MoneyFormatter()); return barData; } private void initDayOfWeekChart(){ dayOfWeekChart.setVisibility(View.GONE); dayOfWeekChart.getXAxis().setDrawGridLines(false); dayOfWeekChart.setBackgroundColor(getResources().getColor(R.color.bgContentTop)); dayOfWeekChart.setDrawGridBackground(false); XAxis xAxis = dayOfWeekChart.getXAxis(); xAxis.setDrawGridLines(true); dayOfWeekChart.getAxisLeft().setDrawGridLines(false); dayOfWeekChart.getAxisLeft().setEnabled(false); dayOfWeekChart.getAxisRight().setDrawGridLines(false); dayOfWeekChart.getAxisRight().setEnabled(false); dayOfWeekChart.getXAxis().setDrawGridLines(false); dayOfWeekChart.getLegend().setEnabled(false); dayOfWeekChart.getAxisRight().setDrawLabels(false); dayOfWeekChart.getAxisLeft().setDrawLabels(true); dayOfWeekChart.setTouchEnabled(true); dayOfWeekChart.setDoubleTapToZoomEnabled(false); dayOfWeekChart.getXAxis().setEnabled(true); dayOfWeekChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM); dayOfWeekChart.setPinchZoom(false); dayOfWeekChart.setDrawBarShadow(false); dayOfWeekChart.setDrawGridBackground(false); dayOfWeekChart.setOverScrollMode(View.SCROLL_AXIS_HORIZONTAL); dayOfWeekChart.getDescription().setEnabled(false); dayOfWeekChart.setScaleEnabled(false); dayOfWeekChart.setVisibleXRangeMaximum(7); xAxis.setValueFormatter(new DateForFormatter()); dayOfWeekChart.animateY(1500); dayOfWeekChart.invalidate(); dayOfWeekChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { loadDetailStatistic((int)e.getX()-1,false,StatisticWeeklyCatching.getOrderCatching().get((int)e.getX()-1)); } @Override public void onNothingSelected() { } }); } private void initDayOfMonthChart(){ dayOfMonthChart.setVisibility(View.GONE); dayOfMonthChart.getXAxis().setDrawGridLines(false); dayOfMonthChart.setBackgroundColor(getResources().getColor(R.color.bgContentTop)); dayOfMonthChart.setDrawGridBackground(false); XAxis xAxis = dayOfMonthChart.getXAxis(); xAxis.setDrawGridLines(true); dayOfMonthChart.getAxisLeft().setDrawGridLines(false); dayOfMonthChart.getAxisLeft().setEnabled(false); dayOfMonthChart.getAxisRight().setDrawGridLines(false); dayOfMonthChart.getAxisRight().setEnabled(false); dayOfMonthChart.getXAxis().setDrawGridLines(false); dayOfMonthChart.getLegend().setEnabled(false); dayOfMonthChart.getAxisRight().setDrawLabels(false); dayOfMonthChart.getAxisLeft().setDrawLabels(true); dayOfMonthChart.setTouchEnabled(true); dayOfMonthChart.setDoubleTapToZoomEnabled(false); dayOfMonthChart.getXAxis().setEnabled(true); dayOfMonthChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM); dayOfMonthChart.setPinchZoom(false); dayOfMonthChart.setDrawBarShadow(false); dayOfMonthChart.setDrawGridBackground(false); dayOfMonthChart.setOverScrollMode(View.SCROLL_AXIS_HORIZONTAL); dayOfMonthChart.getDescription().setEnabled(false); dayOfMonthChart.setScaleEnabled(false); dayOfMonthChart.setVisibleXRangeMaximum(10); dayOfMonthChart.animateY(1500); dayOfMonthChart.invalidate(); dayOfMonthChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { loadDetailStatistic((int)e.getX()-1,true,StatisticMonthlyCatching.getOrderCatching().get((int)e.getX()-1)); } @Override public void onNothingSelected() { } }); } private int getCurrentDateIndexInWeek(){ Calendar calendar = Calendar.getInstance(); int index = calendar.get(Calendar.DAY_OF_WEEK); if (index==1) return 6;//CN index 1->6 return index-2;//Còn lại index giảm 2 } private String getCurrentDateByIndex(int index, boolean isMonth){ Calendar calendar = Calendar.getInstance(); if (isMonth){ calendar.set(Calendar.DAY_OF_MONTH,index+1); }else{ int dayOfWeek = getCurrentDateIndexInWeek(); calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH,index - dayOfWeek); } return Helper.dateFormat.format(calendar.getTime()); } class DateForFormatter implements IAxisValueFormatter { String[] days = {"","Thứ 2", "Thứ 3", "Thứ 4", "Thứ 5", "Thứ 6", "Thứ 7", "CN"}; public DateForFormatter(){} @Override public String getFormattedValue(float value, AxisBase axis) { if(value>=0){ return days[(int)value]; } else{ return ""; } } @Override public int getDecimalDigits() { return 0; } } class MoneyFormatter implements IValueFormatter { @Override public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { if (value==0) return ""; return (int)value/1000 + "K"; } } }<file_sep>/app/src/main/java/com/foa/driver/model/StatisticItem.java package com.foa.driver.model; import com.google.gson.annotations.SerializedName; public class StatisticItem { @SerializedName("income") private long income; @SerializedName("commission") private long commission; @SerializedName("numOrderFinished") private int numOrderFinished; public long getIncome() { return income; } public void setIncome(long income) { this.income = income; } public long getCommission() { return commission; } public void setCommission(long commission) { this.commission = commission; } public int getNumOrderFinished() { return numOrderFinished; } public void setNumOrderFinished(int numOrderFinished) { this.numOrderFinished = numOrderFinished; } public long getTotalShippingFee(){ return income+ commission; } } <file_sep>/app/src/main/java/com/foa/driver/network/body/ApproveDepositBody.java package com.foa.driver.network.body; import com.google.gson.annotations.SerializedName; public class ApproveDepositBody { @SerializedName("paypalOrderId") private String paypalOrderId; public ApproveDepositBody(String paypalOrderId) { this.paypalOrderId = paypalOrderId; } } <file_sep>/app/src/main/java/com/foa/driver/model/enums/StatisticType.java package com.foa.driver.model.enums; public enum StatisticType { DAY, WEEK, MONTH }
b13286ca7c4ca24c276697bff9d0c5957526b82c
[ "Java", "Gradle" ]
26
Java
Food-Ordering-Application/driver-android
8d270def30cedb7100861cc362cd72e70213fdba
d01ea2c9d9ded1d122447ab635e74bbd5485454e
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Models\Articles; use Illuminate\Http\Request; class BlogController extends Controller { /** * @Get("/articles") */ public function articles() { $articles = Articles::all(); return view('articles', [ 'articles' => $articles ]); } /** * @Get("/article/{id}") */ public function article( $slug = null) { return view('article', [ 'slug' => $slug ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class Mails extends Model { use Notifiable; const EMAIL = 'email'; const SUBJECT = 'subject'; const CONTENT = 'content'; protected $fillable = [ 'email', 'subject', 'content', ]; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Validator; use App\Models\Mails; use App\Notifications\form; /** * @Middleware("web") */ class ContactController extends Controller { /** * @Get("/contact") */ public function contact() { return view('contact', [ 'message' => session('message') ]); } /** * @Post("/contact") */ public function postContact(Request $request) { $values = $request->all(); $validator = Validator::make($values, [ 'email' => 'required', 'subject' => 'required', 'content' => 'required' ]); if($validator->fails()) { return redirect()->action('ContactController@contact')->with('message', 'Tous les champs sont obligatoires'); } $mail = Mails::create([ Mails::EMAIL => $values[Mails::EMAIL], Mails::SUBJECT => $values[Mails::SUBJECT], Mails::CONTENT => $values[Mails::CONTENT] ]); Notification::send($mail, new form($mail)); return redirect()->action('ContactController@contact')->with('message', 'Your mail is send.'); } }
4d99e1c24369cd448769bf2b5da8765e72d8a381
[ "PHP" ]
3
PHP
chouti44/laravelCecileLivetA2dev
9d8c6949fd0fc65ccb7537eb4d0f549735caa162
a0eaaab8ff5cb28520988dcae69c2bfb28f2a196
refs/heads/master
<file_sep>'use strict'; var fs = require('fs-extra'); var expect = require('chai').expect; var Entry = require('../lib/entry'); var FIXTURE_DIR = 'fixture'; require('chai').config.truncateThreshold = 0; describe('Entry', function() { describe('constructor', function() { var size = 1337; var mtime = Date.now(); it('supports omitting mode for files', function() { var entry = new Entry('/foo.js', size, mtime); expect(entry.relativePath).to.equal('/foo.js'); expect(entry.size).to.equal(size); expect(entry.mtime).to.equal(mtime); expect(entry.mode).to.equal(0); expect(entry.isDirectory()).to.not.be.ok; }); it('supports omitting mode for directories', function() { var entry = new Entry('/foo/', size, mtime); expect(entry.relativePath).to.equal('/foo/'); expect(entry.size).to.equal(size); expect(entry.mtime).to.equal(mtime); expect(entry.mode).to.equal(16877); expect(entry.isDirectory()).to.be.ok; }); it('supports including manually defined mode', function() { var entry = new Entry('/foo.js', size, mtime, 1); expect(entry.relativePath).to.equal('/foo.js'); expect(entry.size).to.equal(size); expect(entry.mtime).to.equal(mtime); expect(entry.mode).to.equal(1); expect(entry.isDirectory()).to.not.be.ok; }); it('errors on a non-number mode', function() { expect(function() { return new Entry('/foo.js', size, mtime, '1'); }).to.throw('Expected `mode` to be of type `number` but was of type `string` instead.') }); }); describe('.fromStat', function() { afterEach(function() { fs.removeSync(FIXTURE_DIR); }); it('creates a correct entry for a file', function() { var path = FIXTURE_DIR + '/index.js'; fs.outputFileSync(path, ''); try { var stat = fs.statSync(path); var entry = Entry.fromStat(path, stat); expect(entry.isDirectory()).to.not.be.ok; expect(entry.mode).to.equal(stat.mode); expect(entry.size).to.equal(stat.size); expect(entry.mtime).to.equal(stat.mtime); expect(entry.relativePath).to.equal(path); } finally { fs.unlinkSync(path); } }); it('creates a correct entry for a directory', function() { var path = FIXTURE_DIR + '/foo/'; fs.mkdirpSync(path); var stat = fs.statSync(path); var entry = Entry.fromStat(path, stat); expect(entry.isDirectory()).to.be.ok; expect(entry.mode).to.equal(stat.mode); expect(entry.size).to.equal(stat.size); expect(entry.mtime).to.equal(stat.mtime); expect(entry.relativePath).to.equal(path); }); }); }); <file_sep>// validate that these type annotations at least type check import * as FSTree from '../lib/index';
3080dac0d08c8968d710f52677f6cc4639a96214
[ "JavaScript", "TypeScript" ]
2
JavaScript
ef4/fs-tree-diff
2f5877d7aacf05def588ca82daa8068ea44d9d81
555cfabaedd7e85ea24f2a3ec922389c724b2b82
refs/heads/master
<file_sep>#!/usr/bin/python3 import json,os file_name='.credentials.json' full_file=os.path.abspath(os.path.join(file_name)) def credencial(): with open(full_file) as jsonfile: parsed = json.load(jsonfile) servidor = parsed['informacoes']['vsphere'] usuario = parsed['informacoes']['user'] senha = parsed['informacoes']['senha'] return servidor,usuario,senha <file_sep>#!/usr/bin/python3 import atexit import ssl from pyVim import connect from pyVmomi import vim from authentication import credencial servidor,usuario,senha = credencial() def vconnect(): s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE service_instance = connect.SmartConnect(host=servidor, user=usuario, pwd=<PASSWORD>, sslContext=s) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() return content content = vconnect() container = content.rootFolder viewType = [vim.VirtualMachine] recursive = True containerView = content.viewManager.CreateContainerView(container, viewType, recursive) children = containerView.view for child in children: summary = child.summary if summary.runtime.powerState == 'poweredOn': if 'Red Hat Enterprise Linux 7' in summary.config.guestFullName: print(summary.config.name+";"+summary.config.annotation) elif 'Red Hat Enterprise Linux 6' in summary.config.guestFullName: print(summary.config.name+";"+summary.config.annotation) elif 'CentOS 7' in summary.config.guestFullName: print(summary.config.name+";"+summary.config.annotation) elif 'CentOS' in summary.config.guestFullName and not 'CentOS 7' in summary.config.guestFullName: print(summary.config.name+";"+summary.config.annotation) <file_sep># python_vmware_list_machines Este script em python 3 serve para listar as maquinas Linux instaladas dentro de um cluster do VMware, após configuração inicial (instalação de pacotes de dependências), o script se conectará na api do Vsphere e listará todas as máquinas Linux do cluster. O formato da lista será: • máquina;descrição
2733c9c3f9997cfa97b709f83cf66de89e58d9d9
[ "Markdown", "Python" ]
3
Python
laurobmb/List-Vmware-Machines
526dd5a60c0abcf36d4fcdf7748d188eee379053
db1371fe095ffe6806f5f0feed0bebb55d34d1ca
refs/heads/master
<file_sep>using System; using System.IO; using System.Xml; namespace SpellEditor.Sources.Config { public class Config { public enum ConnectionType { SQLite, MySQL } public string Host = "127.0.0.1"; public string User = "root"; public string Pass = "<PASSWORD>"; public string Port = "3306"; public string Database = "SpellEditor"; public string Language = "enUS"; public ConnectionType connectionType = ConnectionType.SQLite; public void WriteConfigFile() => WriteConfigFile(Host, User, Pass, Port, Database, Language); public void WriteConfigFile(string host, string user, string pass, string port, string database, string language) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; using (XmlWriter writer = XmlWriter.Create("config.xml", settings)) { writer.WriteStartDocument(); writer.WriteStartElement("MySQL"); writer.WriteElementString("host", host); writer.WriteElementString("username", user); writer.WriteElementString("password", <PASSWORD>); writer.WriteElementString("port", port); writer.WriteElementString("database", database); writer.WriteElementString("language", language); writer.WriteEndElement(); writer.WriteEndDocument(); } } public void ReadConfigFile() { try { bool hasError = false; using (XmlReader reader = XmlReader.Create("config.xml")) { if (reader.ReadToFollowing("host")) Host = reader.ReadElementContentAsString(); else hasError = true; if (reader.ReadToFollowing("username")) User = reader.ReadElementContentAsString(); else hasError = true; if (reader.ReadToFollowing("password")) Pass = reader.ReadElementContentAsString(); else hasError = true; if (reader.ReadToFollowing("port")) Port = reader.ReadElementContentAsString(); else hasError = true; if (reader.ReadToFollowing("database")) Database = reader.ReadElementContentAsString(); else hasError = true; if (reader.ReadToFollowing("language")) Language = reader.ReadElementContentAsString(); else hasError = true; } if (hasError) WriteConfigFile(Host, User, Pass, Port, Database, Language); } catch (Exception e) { throw new Exception("ERROR: config.xml is corrupt - please delete it and run the program again.\n" + e.Message); } } public void UpdateConfigValue(string key, string value) { if (!File.Exists("config.xml")) return; var xml = new XmlDocument(); xml.Load("config.xml"); var node = xml.SelectSingleNode("MySQL/" + key); if (node == null) return; node.InnerText = value; xml.Save("config.xml"); ReadConfigFile(); } public string GetConfigValue(string key) { var xml = new XmlDocument(); if (!File.Exists("config.xml")) return ""; xml.Load("config.xml"); var node = xml.SelectSingleNode("MySQL/" + key); return node == null ? "" : node.InnerText; } } }
d78db3678ce2bbbe819375808e9ece33927e5e88
[ "C#" ]
1
C#
azerothcore/WoW-Spell-Editor
b99ce21037080d7f7c176eb1e4b5d430a3287cd1
922ab8b6145d9b1606bad02d25be2b703783e0b5
refs/heads/main
<repo_name>Dvangstad/Book-Search-Engine-<file_sep>/README.md # Book-Search-Engine- This is book search engine that allows someone to search for new books to read so that they can keep a list of books to purchase <file_sep>/server/schemas/resolvers.js const { User } = require("../models"); const { signToken } =require("../utils/auth"); const resolvers = { Query: { activeUser: async () => { const userData = await User.find({}); return userData } }, Mutation: { createUser: async (parent, args) => { const newUser = await User.create(args); const token = signToken(newUser) return { token, user } } } } module.exports = resolvers<file_sep>/client/src/utils/mutations.js import { gql } from '@apollo/client'; export const CREATE_USER = gql` mutation createUser($username: String!, $email: String!, $password: String!) { createUser(username: $username, email: $email, password: $password){ token user { _id username email } } } `
c1cfe5326415d514846576bc21f58aa78126f64f
[ "Markdown", "JavaScript" ]
3
Markdown
Dvangstad/Book-Search-Engine-
8d1da416df6d04b1adbcfdcce9a1e92536b300f5
1dc50caa4b435a596695dd109cc6534428a73f6e
refs/heads/master
<file_sep>package com.skillstorm.mobile.Service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.skillstorm.mobile.models.User; import com.skillstorm.mobile.repository.UserRepo; @Service public class UserService { @Autowired private UserRepo ur; /* public User findById(Integer id) { Optional <User> optional= ur.findById(id); if(optional.isPresent()) { return optional.get(); } else { return new User(); } //return null; } */ public User findUser(int id) { // Optional <User> optional= ur.findById(id); Optional<User> optional=ur.findById(id); User tempUser=optional.get(); System.out.println(tempUser); return tempUser; /* if(optional.isPresent()) { } else { return new User(); } */ //return null; } public User saveUser(User user) { User body= ur.save(user); return body; } public User updateUserInfo(User user,int id) { Optional<User> optional=ur.findById(id); User tempUser=optional.get(); return ur.save(tempUser); /* if(ur.findById(user.getUserID()).isPresent()) { return ur.save(user); } else { return new User(); } */ } } <file_sep>package com.skillstorm.mobile.controllers; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.skillstorm.mobile.Service.UserService; import com.skillstorm.mobile.models.User; import com.skillstorm.mobile.repository.UserRepo; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepo ur; @Autowired private UserService us; /* @GetMapping(value="/user") public Optional<User> showUserInfo() { int num=4; User user= us.findById(num); //return Optional.ofNullable(user); System.out.println(user); //return Optional.ofNullable(user); return Optional.of(user); } */ @GetMapping(value="/user") //showing all user info to a User public User showUserInfo() { int num=1; User user= us.findUser(num); return user; } @PostMapping() //Adding User public ResponseEntity<User> insertUser(@RequestBody @Valid User user) { User body= us.saveUser(user); return new ResponseEntity<>(body, HttpStatus.CREATED); } @PutMapping() public User updateUser(@RequestBody User user) { int id=3; return us.updateUserInfo(user,id); //System.out.println(updatedUser); //return updatedUser; } }
e7d9cb816b23148dc67df8c4b944a348b67552f3
[ "Java" ]
2
Java
AbdullahHady/TemporaryRepo
f050b024be8d345eb409c0223d7039c3698def5b
f597b95082903997e6368231542ea6ccc91cc0ad
refs/heads/master
<file_sep>package com.example.simplecalculator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import java.lang.Exception class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val tv = findViewById<TextView>(R.id.tv) val input1 = findViewById<EditText>(R.id.input1) val input2 = findViewById<EditText>(R.id.input2) val add = findViewById<Button>(R.id.add) val sub = findViewById<Button>(R.id.sub) val multi = findViewById<Button>(R.id.multi) val div = findViewById<Button>(R.id.div) add.setOnClickListener { if(input1.text.isNotEmpty() && input2.text.isNotEmpty()){ tv.text = "${input1.text.toString().toDouble() + input2.text.toString().toDouble()}" }else{ Toast.makeText(this, "Please, Enter Numbers", Toast.LENGTH_LONG).show() } } sub.setOnClickListener { if(input1.text.isNotEmpty() && input2.text.isNotEmpty()){ tv.text = "${input1.text.toString().toDouble() - input2.text.toString().toDouble()}" }else{ Toast.makeText(this, "Please, Enter Numbers", Toast.LENGTH_LONG).show() } } multi.setOnClickListener { if(input1.text.isNotEmpty() && input2.text.isNotEmpty()){ tv.text = "${input1.text.toString().toDouble() * input2.text.toString().toDouble()}" }else{ Toast.makeText(this, "Please, Enter Numbers", Toast.LENGTH_LONG).show() } } div.setOnClickListener { if(input1.text.isNotEmpty() && input2.text.isNotEmpty()){ try { tv.text = "${input1.text.toString().toDouble() / input2.text.toString().toDouble()}" }catch (e: Exception){ Toast.makeText(this, "You Can't Divide By Zero", Toast.LENGTH_LONG).show() tv.text = "" } }else{ Toast.makeText(this, "Please, Enter Numbers", Toast.LENGTH_LONG).show() } } } }
7c22b8017c9f1526fa2ee0cb309855e7db31dca2
[ "Kotlin" ]
1
Kotlin
hsn-amr/Simple-Calculator
1750433778df8d6daee43115e2faf3dff10bcc55
c0d8cf717063bbffd938cc94d1e72c993225d2f1
refs/heads/master
<repo_name>SubhamGupta007/Weather_App<file_sep>/src/components/Wheather.jsx import { Box, makeStyles } from '@material-ui/core'; import logo from '../images/back.png' import Form from './Form' const useStyles = makeStyles({ component: { justifyContent: 'center', alignItems: 'center', display: 'flex', height: '100vh', background: '#7f53ac', backgroundImage: 'linear-gradient(315deg, #7f53ac 0%, #647dee 74%)' }, leftcontainer: { backgroundImage: `url(${logo})`, height: `90vh`, width: `30vw`, background: 'cover', borderRadius: '10% 0 0 10%' }, rightcontainer: { background: '#7252DB', height: '90vh', width: '40vw' } }) const Wheather = () => { const classes = useStyles() return ( <Box className={classes.component}> <Box className={classes.leftcontainer}> </Box> <Box className={classes.rightcontainer}> <Form /> </Box> </Box> ) } export default Wheather<file_sep>/src/App.js import Wheather from './components/Wheather' function App() { return ( <Wheather /> ); } export default App; <file_sep>/src/components/Form.jsx import { Box, TextField, Button, makeStyles } from '@material-ui/core' import { getdata } from './api' import { useEffect, useState } from 'react' import Information from './Information' const usestyle = makeStyles({ component: { }, input: { color: '#fff', marginRight: '1em', outline: 'red' }, button: { marginTop: '1em', } }) const Form = () => { const [data, getdatawheather] = useState(); const [city, setcity] = useState(''); const [country, setcountry] = useState(''); const [click, handleclick] = useState(false); useEffect(() => { const getwheather = async () => { city && await getdata(city, country).then(response => { getdatawheather(response.data); console.log(response.data); }) } getwheather(); handleclick(false); }, [click]); const classes = usestyle(); const handlecitychange = (value) => { setcity(value); } const handlecountrychange = (value) => { setcountry(value); } return ( <> <Box className={classes.component}> <TextField id="filled-basic" color="secondary" onChange={(e) => handlecitychange(e.target.value)} inputProps={{ className: classes.input }} label='City' className={classes.input} /> <TextField color="secondary" onChange={(e) => handlecountrychange(e.target.value)} inputProps={{ className: classes.input }} label='Country' className={classes.input} /> <Button variant="contained" color="secondary" className={classes.button} onClick={() => handleclick(true)}> Get Wheather </Button> <Information data={data} /> </Box> </> ) } export default Form
706b149fb49dc4344efc6bf3b9d72dfd48aca4c1
[ "JavaScript" ]
3
JavaScript
SubhamGupta007/Weather_App
d21d8acf912d3b2926aa424c315f051d49cdaadc
2b018e3b7aaa6e81e5073e580e4705fdc818fa6e
refs/heads/master
<repo_name>puffyelms/PayupDashboard<file_sep>/src/main/webapp/js/app/payup-poc/payup-poc-fm-filter-dropdown-directive.js (function() { angular.module('appPayupPoc') .directive('fmFilterDropdown', function() { return { scope: { dropdownList : '=', dropdownSelected : '=', dropdownLabel : '@', dropdownWidth : '@dropdownWidth' }, templateUrl: "templates/fm-filter-dropdown-template.html", restrict: 'E', controller: function($scope) { $scope.dropdownStyleWidth = ""; if ($scope.dropdownWidth != null) { // Add dropdown combobox width style $scope.dropdownStyleWidth = "width:" + $scope.dropdownWidth; } } } }); }());<file_sep>/src/main/webapp/js/app/app-payup-poc.js (function() { // declare app module angular.module('appPayupPoc', ['wj']); }());<file_sep>/src/main/webapp/js/app/payup-poc/payup-poc-controller.js (function() { angular.module('appPayupPoc') .controller('appCtrl', function appCtrl($scope, $timeout, dataService) { var payupCtrl = this; var pollingTimer = null; payupCtrl.pollingStarted = false; //Column headers payupCtrl.payupGridColumnsDefinition = []; payupCtrl.payupGridData = []; payupCtrl.storyList = [ "All" ]; payupCtrl.storySelected = "All"; payupCtrl.operationTypeList = [ "View", "Edit" ]; payupCtrl.operationTypeSelected = "View"; payupCtrl.productGroupList = []; payupCtrl.productGroupSelected = null; payupCtrl.couponList = []; payupCtrl.couponListMinSelected = null; payupCtrl.couponListMaxSelected = null; payupCtrl.viewTypeRangeOptions = []; payupCtrl.viewTypeRangeSelected = null; payupCtrl.settlementDate = ""; dataService.getFullPageLoad() .then(getFullPageLoadSuccess, null, getNotification) .catch(errorCallback) .finally(getFullPageLoadComplete); // use the "initialized" event to initialize the multiple header rows $scope.init = function (s, e) { //var flex = panel.grid; //flex.beginUpdate(); //for (var i = 0; i < 3; i++) { if (s.columnHeaders.rows.length < 2) { var hr = new wijmo.grid.Row(); s.columnHeaders.rows.push(hr); } // add some data to the column headers var colDef = payupCtrl.payupGridColumnsDefinition; for (var r = 0; r < s.columnHeaders.rows.length; r++) { if (r==0) { for (var c = 0; c < s.columns.length; c++) { var content = colDef[c].header;// 'r:' + r + ',c:' + c; s.columnHeaders.setCellData(r, c, content); } } if (r==1) { for (var c = 0; c < s.columns.length; c++) { if (c == 0) { s.columnHeaders.setCellData(r, c, "Settlement Date"); } else { s.columnHeaders.setCellData(r, c, payupCtrl.settlementDate); } } } } s.autoSizeColumns(); //flex.endUpdate(); } $scope.itemFormatter = function (panel, r, c, cell) { console.log("Called itemFormatter"); //if (panel.cellType == wijmo.grid.CellType.Cell) { // // //if its calculated column // if (r <=3 && c > 0) { // var flex = panel.grid; // flex.beginUpdate(); // //get data from other columns for this row i.e. profilt=sales-expenses // //var calculatedData = parseInt(flex.getCellData(r, 1, false)) - parseInt(flex.getCellData(r, 2, false)); // //set the value in the calculated column // //cell.innerHTML = "<input type='radio' />"; // cell.innerHTML = "<div style='border: solid 1px black; color: green; background-color: pink;'>"+flex.getCellData(r, c, false)+"</div>"; // // flex.setCellData(r, c, calculatedData, true); // flex.endUpdate(); // } //} } payupCtrl.itemsSourceChanged = function(sender, args) { console.log("Auto Sizing Columns"); sender.autoSizeColumns(); }; function getFullPageLoadSuccess(allData) { payupCtrl.payupGridColumnsDefinition = allData.gridColumns; payupCtrl.payupGridData = new wijmo.collections.CollectionView(allData.gridData); payupCtrl.settlementDate = allData.settlementDate; payupCtrl.payupGridData.moveCurrentToPosition(-1); // Clears selection of first cell from table payupCtrl.couponList = allData.couponList; payupCtrl.couponListMinSelected = allData.minCoupon; payupCtrl.couponListMaxSelected = allData.maxCoupon; payupCtrl.productGroupList = allData.productGroupList; payupCtrl.productGroupSelected = allData.selectedProductGroup;//allData.productGroupList[0]; payupCtrl.viewTypeRangeOptions = allData.viewTypeList; payupCtrl.viewTypeRangeSelected = allData.selectedView; } function getFullGridLoadSuccess(allData) { payupCtrl.payupGridColumnsDefinition = allData.gridColumns; payupCtrl.payupGridData = new wijmo.collections.CollectionView(allData.gridData); payupCtrl.settlementDate = allData.settlementDate; payupCtrl.payupGridData.moveCurrentToPosition(-1); // Clears selection of first cell from table } function getNotification(notification) { console.log('Promise Notifcation:' + notification); } function getFullPageLoadComplete() { console.log('getFullPageLoadComplete has completed'); continuePollingIfNotHalted(); } function errorCallback(errorMsg) { console.log('Error message:' + errorMsg); $timeout.cancel(pollingTimer); poller(); payupCtrl.pollingStarted = true; } $scope.$watchGroup(['payupCtrl.viewTypeRangeSelected','payupCtrl.couponListMinSelected','payupCtrl.couponListMaxSelected', 'payupCtrl.productGroupSelected'], function(newVal, oldVal, scope){ if (oldVal!= null && oldVal.length > 0 && (oldVal[0] != null || oldVal[1] != null || oldVal[2] != null || oldVal[3] != null) ){ // Don't call service on intial setting of viewTypeSelected pausePollingDuringServerCall(); console.log('viewTypeSelected changed:', newVal, ":", oldVal); dataService.getFullPageLoad(payupCtrl.productGroupSelected, newVal, payupCtrl.couponListMinSelected, payupCtrl.couponListMaxSelected) .then(getFullGridLoadSuccess, null, getNotification) .catch(errorCallback) .finally(getFullPageLoadComplete); } }); payupCtrl.refreshDataClick = function () { pausePollingDuringServerCall(); console.log("Previous Selected Product Group DID change so do full page refresh"); dataService.getFullPageLoad(payupCtrl.productGroupSelected, payupCtrl.viewTypeRangeSelected, payupCtrl.couponListMinSelected, payupCtrl.couponListMaxSelected) .then(getFullGridLoadSuccess, null, getNotification) .catch(errorCallback) .finally(getFullPageLoadComplete); }; function getGridDataComplete() { console.log('getGridDataComplete has completed'); continuePollingIfNotHalted(); } payupCtrl.pollingGridData = function () { dataService.getGridData(payupCtrl.productGroupSelected, payupCtrl.viewTypeRangeSelected, payupCtrl.couponListMinSelected, payupCtrl.couponListMaxSelected) .then(getGridDataSuccess, null, getNotification) .catch(errorCallback) .finally(getPollingGridDataComplete); }; function getGridDataSuccess(refreshGridData) { console.log("Product Selected=" + payupCtrl.productGroupSelected ); var flex = $scope.flex; console.log("flex="+flex); flex.collectionView.beginUpdate(); var newList = refreshGridData.gridData; var list = flex.collectionView.sourceCollection; if (newList) { for (var i = 0; i < newList.length; i++) { var newProductToUpdate = newList[i].product; for (var ii = 0; ii < list.length; ii++) { if (list[ii].product == newProductToUpdate) { list[ii] = newList[i]; } } } } payupCtrl.payupGridColumnsDefinition = refreshGridData.gridColumns; flex.collectionView.endUpdate(); flex.collectionView.refresh(); payupCtrl.payupGridData.moveCurrentToPosition(-1); // Clears selection of first cell from table } var poller = function() { pollingTimer = $timeout(payupCtrl.pollingGridData, 2000); } // After finally block of refresh grid, call poller again. function getPollingGridDataComplete() { console.log('getPollingGridDataComplete has completed'); continuePollingIfNotHalted(); } var continuePollingIfNotHalted = function() { console.log('continuePollingIfNotHalted called'); $timeout.cancel(pollingTimer); payupCtrl.pollingStarted = true; poller(); } var pausePollingDuringServerCall = function() { console.log('pausing polling called'); payupCtrl.pollingStarted = false; $timeout.cancel(pollingTimer); } }); }()); <file_sep>/src/main/webapp/js/app/payup-poc/payup-poc-routes.js (function() { angular.module('appPayupPoc', ['ngRoute', 'wj']) .config(['$logProvider','$routeProvider', function($logProvider,$routeProvider) { $logProvider.debugEnabled(true); $routeProvider .when('/', { controller: 'appCtrl', controllerAs: 'payupCtrl', templateUrl: 'templates/home.html' }) .otherwise('/'); //$stateProvider // .state('home', { // url: '/', // template: '<h1>This is inline template</h1>' // //templateUrl: 'app/templates/home.html' // }); }]); }());
5482511b1cd57858cfcb3350f756dbf69738747c
[ "JavaScript" ]
4
JavaScript
puffyelms/PayupDashboard
74f0ef6b27f4a763dbdbaff0f351f41d95613c65
270082da5e55995e0df393adad7a27466b01f804
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IRuleService : IGenericService<Rule, Record> { } } <file_sep>using System; namespace S3.WebUI.cBlazor.Models { public class Address { public string Id { get; private set; } public string Line1 { get; set; } public string? Line2 { get; set; } public string Town { get; set; } public string State { get; set; } public string Country { get; set; } } public class StudentAddress : Address { public string StudentId { get; set; } public virtual Student Student { get; set; } } public class TeacherAddress : Address { public string TeacherId { get; set; } public virtual Teacher Teacher { get; set; } } public class ParentAddress : Address { public string ParentId { get; set; } public virtual Parent Parent { get; set; } } public class SchoolAddress : Address { public string SchoolId { get; set; } public virtual School School { get; set; } } } <file_sep> using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class SchoolStatistics : BaseEntity { public string Name { get; set; } public string Category { get; set; } // Primary, Secondary //***TODO: an enumeration might be better public string Email { get; set; } public string PhoneNumber { get; set; } public string Administrator { get; set; } public string AdministratorId { get; set; } public string Location { get; set; } public int NumberOfTeachers { get; set; } public int NumberOfClasses { get; set; } public int NumberOfStudents { get; set; } } }<file_sep> //namespace S3.WebUI.cBlazor.Models //{ // public class State // { // public string[] States { get; set; } // } //} <file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class ParentService : HttpService<Parent, Registration>, IParentService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public ParentService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) : base(httpClient, appSettings, configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<Parent> GetAsync(string regNumber) { var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["get"], "variable", $"reg/Parents"); return await _httpClient.GetJsonAsync<Parent>($"{_appSettings.ApiUrl}/{endpoint}/{regNumber}"); } } } <file_sep>namespace S3.WebUI.cBlazor.Shared.Models { public sealed class SignIn { public string Username { get; set; } public string Password { get; set; } } }<file_sep>using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { /// <summary> /// / Not to be stored in the database. For reports generation only /// </summary> public class ClassReport { //public string ClassName { get; set; } public ICollection<StudentReport> StudentReports { get; set; } public ScoresStat ScoresStat { get; set; } } public class StudentReport { public string StudentName { get; set; } public ICollection<TermReport> TermReports { get; set; } } public class TermReport { public string Term { get; set; } public ICollection<SubjectReport> SubjectReports { get; set; } } public class SubjectReport { public string Subject { get; set; } public float? HomeworkScore { get; set; } public float? ClassActivitiesScore { get; set; } public float? CAScore { get; set; } public float? FirstExamScore { get; set; } public float? SecondExamScore { get; set; } public float? WeightedScore { get; set; } public char? Grade { get; set; } } public class ScoresStat { public ICollection<TermStat> TermStats { get; set; } } public class TermStat { public string Term { get; set; } public ICollection<Stat> Stats { get; set; } } public class Stat { public string Subject { get; set; } public float ClassMinScore { get; set; } public float ClassMaxScore { get; set; } public float ClassAverageScore { get; set; } } } <file_sep> using PuppeteerSharp; using PuppeteerSharp.Media; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Threading.Tasks; //using IronPdf; public static class PdfGenerator { public static async Task GenerateAsync(ClassReport classReport, Class selectedClass, int session, string[] classSubjects) { try { //Renderer.RenderHtmlAsPdf("<h1>Hello World<h1>").SaveAs("test.pdf"); //var renderer = new HtmlToPdf(); //var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>"); //pdf.SaveAs("test.pdf"); Console.WriteLine("Inside Generator"); //Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(classSubjects, new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase })); // downloads chromium to a temp folder, you can also specify a specific version, or a location where it should look for chromium. await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); Console.WriteLine("Downloaded Browser"); using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }); Console.WriteLine("Set headless = false"); using var page = await browser.NewPageAsync(); Console.WriteLine("Executed: using var page = await browser.NewPageAsync();"); var reportCardString = PdfReportCardHtmlTemplate.GetHTMLString(classReport, selectedClass, session, classSubjects); Console.WriteLine("Executed: reportCardString as follows:"); Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(reportCardString, new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase })); await page.SetContentAsync(reportCardString); Console.WriteLine("Executed: await page.SetContentAsync(reportCardString);"); await page.GetContentAsync(); Console.WriteLine("Executed: await page.GetContentAsync();"); await page.PdfAsync("ReportCard.pdf", new PdfOptions { DisplayHeaderFooter = false, Format = PaperFormat.A4, Landscape = true, }); Console.WriteLine("End of Generator"); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } //using DinkToPdf; //using System; //using System.Collections.Generic; //using System.IO; //using S3.WebUI.cBlazor.Models; //namespace S3.WebUI.cBlazor.Utility //{ // public static class PdfSettingsHelper // { // public static GlobalSettings GetGlobalSettings() // { // return new GlobalSettings // { // ColorMode = ColorMode.Color, // Orientation = Orientation.Landscape, // PaperSize = PaperKind.A4, // Margins = new MarginSettings { Top = 10 }, // DocumentTitle = "Report Card" // //Out = @"D:\PDFCreator\Employee_Report.pdf" // }; // } // public static ObjectSettings GetObjectSettings(ClassReport classReport, Class selectedClass, int session, string[] classSubjects) // { // var pdfStyleSheetPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\css", "pdf-report-card.css"); // return new ObjectSettings // { // PagesCount = false, // HtmlContent = PdfReportCardHtmlTemplate.GetHTMLString(classReport, selectedClass, session, classSubjects), // WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = pdfStyleSheetPath }, // //HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]" }, // //FooterSettings = { FontName = "Arial", FontSize = 7, Line = true, Left = "Confidence Cooperative Ltd.", Center = "Statement of Account", Right = DateTime.Now.Date.ToShortDateString() } // }; // } // } //} <file_sep>using System; using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class Class : BaseEntity { public string Name { get; set; } public string Category { get; set; } public string Subjects { get; set; } public string[] SubjectsArray { get; set; } // Navigation properties public string SchoolId { get; set; } public virtual School School { get; set; } public string? ClassTeacherId { get; set; } public virtual Teacher ClassTeacher { get; set; } public string? AssistantTeacherId { get; set; } public virtual Teacher AssistantTeacher { get; set; } public virtual ICollection<Student> Students { get; set; } } } <file_sep>using System.Threading.Tasks; using S3.WebUI.cBlazor.Shared.Models; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IAuthService { Task<IdentityTokens> GetIdentityTokensAsync(); Task SetIdentityTokensAsync(IdentityTokens identityTokens); Task RemoveIdentityTokensAsync(); } } //using System.Threading.Tasks; //namespace S3.WebUI.cBlazor.Shared.Services.Interface //{ // public interface IAuthService // { // Task<string> GetAccessTokenAsync(); // Task SetAccessTokenAsync(string accessToken); // Task RemoveAccessTokenAsync(); // } //}<file_sep>using Blazored.LocalStorage; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services.Interface; using System; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class IdentityService : IIdentityService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public IdentityService(HttpClient httpClient, AppSettings appSettings, IConfiguration configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task SignUpAsync(SignUp signUp) => await _httpClient.PostJsonAsync($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["signUp"]}", signUp); public async Task<IdentityTokens> SignInAsync(SignIn signIn) => await _httpClient.PostJsonAsync<IdentityTokens>($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["signIn"]}", signIn); public async Task RemoveSignUpAsync(string userId) => await _httpClient.DeleteAsync($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["removeSignup"]}/{userId}"); public async Task ChangePasswordAsync(ChangePassword changePassword) => await _httpClient.PutJsonAsync($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["changePassword"]}", changePassword); public async Task ResetPasswordAsync(ResetPassword resetPassword) => await _httpClient.PutJsonAsync($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["resetPassword"]}", resetPassword); public async Task UpdateRolesAsync(UpdateRoles updateRoles) => await _httpClient.PutJsonAsync($"{_appSettings.ApiUrl}/{_configuration.GetSection("endpoints")["updateRoles"]}", updateRoles); } }<file_sep>//using Microsoft.AspNetCore.Components; //using S3.WebUI.cBlazor.Models; //using S3.WebUI.cBlazor.Utility; //using System; //using System.Collections.Generic; //using System.Linq; //using System.Net.Http; //using System.Threading.Tasks; //namespace S3.WebUI.cBlazor.Shared.Services.Interface //{ // public interface IClassSubjectScoresService : IGenericService<ClassSubjectScores, Record> // { // //Task<ClassSubjectScores> FindAsync(string? schoolId, string? classId, string? subject, string? examType, // // string? term, int? session, string[]? include = null); // } //} <file_sep>using System.Net.Http; namespace S3.WebUI.cBlazor.Utility { public enum Mode { None, Add, Clone, Update, Delete, SignUp, ResetPassword, UpdateStudentSubjects, UpdateStudentParent } } <file_sep> using FluentValidation; using System; namespace S3.WebUI.cBlazor.Models.Validators { public class SchoolValidator : AbstractValidator<School> { public SchoolValidator() { RuleFor(x => x.Name) .NotEmpty().WithMessage("Name is required.") .MinimumLength(2).WithMessage("Name is too short.") .MaximumLength(100).WithMessage("Name is too long. Maximum of 100 characters is allowed."); RuleFor(x => x.Category) .NotEmpty().WithMessage("Category is required."); RuleFor(x => x.Email) .NotEmpty().WithMessage("Email address is required.") .EmailAddress().When(y => !string.IsNullOrEmpty(y.Email)).WithMessage("Invalid email address.") .MaximumLength(30).WithMessage("Email address is too long. Maximum of 30 characters is allowed."); RuleFor(x => x.PhoneNumber) .NotEmpty().WithMessage("Phone number is required.") .MaximumLength(50).WithMessage("Phone number is too long. Maximum of 30 characters is allowed."); RuleFor(x => x.Address) .NotNull().WithMessage("School's address is required.") .SetValidator(new AddressValidator()); } } } <file_sep> $(document).ready(function () { downloadReportCards = function () { var pdf = new jsPDF('l', 'pt', 'a4'); //pdf.setTextColor(255, 0, 0); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. var source = $('#all-report-cards')[0]; //var source1 = $('#all-report-cards'); //var source2 = document.getElementById('all-report-cards'); //var source3 = document.getElementById('all-report-cards')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. //specialElementHandlers = { // // element with id of "bypass" - jQuery style selector // '#bypassme': function (element, renderer) { // // true = "handled elsewhere, bypass text extraction" // return true // } //}; margins = { top: 80, bottom: 60, left: 40, width: 600 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case //pdf.fromHTML( // source, // HTML string or DOM elem ref. // margins.left, // x coord // margins.top, // { // y coord // 'width': margins.width // max width of content on PDF // //'elementHandlers': specialElementHandlers // }, // function (dispose) { // // dispose: object with X, Y of the last line add to the PDF // // this allow the insertion of new lines after html // pdf.save('Report Cards.pdf'); // }, margins //); var doc = new jsPDF('l', 'pt', 'a4'); doc.addHTML(document.getElementById('all-report-cards'), 200, 200, {}, function () { doc.save('test.pdf'); }); //var doc = new jsPDF() //doc.text(10, 10, $('.all-report-cards')) ////doc.autoPrint() //doc.save('test.pdf') } //downloadReportCards = function (filename, bytesBase64) { // if (navigator.msSaveBlob) { // //Download document in Edge browser // var data = window.atob(bytesBase64); // var bytes = new Uint8Array(data.length); // for (var i = 0; i < data.length; i++) { // bytes[i] = data.charCodeAt(i); // } // var blob = new Blob([bytes.buffer], { type: "application/octet-stream" }); // navigator.msSaveBlob(blob, filename); // } // else { // var link = document.createElement('a'); // link.download = filename; // link.href = "data:application/octet-stream;base64," + bytesBase64; // document.body.appendChild(link); // Needed for Firefox // link.click(); // document.body.removeChild(link); // } //} //function printPreviewItem(idSelector) { // //var restorePage = document.body.innerHTML; // //var printContent = document.getElementById(idSelector).innerHTML; // //document.body.innerHTML = printContent; // //window.print(); // //document.body.innerHTML = restorePage; // //var prtContent = document.getElementById(idSelector); // //var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0'); // //WinPrint.document.write(prtContent.innerHTML); // //WinPrint.document.close(); // //WinPrint.focus(); // //WinPrint.print(); // //WinPrint.close(); //} });<file_sep>//using Microsoft.AspNetCore.Components; //using Microsoft.Extensions.Configuration; //using S3.WebUI.cBlazor.Models; //using S3.WebUI.cBlazor.Shared.Models; //using S3.WebUI.cBlazor.Shared.Services; //using S3.WebUI.cBlazor.Shared.Services.Interface; //using S3.WebUI.cBlazor.Utility; //using System; //using System.Collections.Generic; //using System.Linq; //using System.Net.Http; //using System.Text; //using System.Text.Json; //using System.Text.RegularExpressions; //using System.Threading.Tasks; //namespace S3.WebUI.cBlazor.Shared.Services //{ // public class ClassSubjectScoresService : HttpService<ClassSubjectScores, Record>, IClassSubjectScoresService // { // private readonly HttpClient _httpClient; // private readonly AppSettings _appSettings; // private readonly IConfiguration _configuration; // public ClassSubjectScoresService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) // : base(httpClient, appSettings, configuration) // => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); // //public async Task<StudentScore> FindAsync(string? schoolId, string? classId, string? subject, string? examType, // // string? term, int? session, string[]? include = null) // //{ // // var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", $"rec/ClassSubjectScores"); // // var classSubjectScores = await _httpClient.GetJsonAsync<StudentScore[]>($"{_appSettings.ApiUrl}/{endpoint}" + // // $"{IncludeStringHelper.GetString(include)}schoolId={schoolId}&classId={classId}&subject={subject}" + // // $"examType={examType}&term={term}&session={session}"); // // return classSubjectScores?.FirstOrDefault(); // //} // } //} <file_sep>using System.Threading.Tasks; using Microsoft.AspNetCore.Components; namespace S3.WebUI.cBlazor.Utility { public static class HttpClientHelper { public static Task<T> GetJSONAsync<T>(this System.Net.Http.HttpClient client, string url) { return client.GetJsonAsync<T>(requestUri: url); } } } <file_sep> //namespace S3.WebUI.cBlazor.Models //{ // public class Subject // { // public string[] Subjects { get; set; } // } //} <file_sep> using System; namespace S3.WebUI.cBlazor.Models { public class ScoresEntryTask : SchoolTask { public string TeacherId { get; set; } public string TeacherName { get; set; } public virtual Teacher Teacher { get; set; } public string Subject { get; set; } public string ClassId { get; set; } public string ClassName { get; set; } public virtual Class Class { get; set; } public string RuleId { get; set; } // The rule to be used to determine the weight of this score and grade obtained in this subject } }<file_sep>using System; using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Models { public class SchoolTask : BaseEntity { public string SchoolId { get; set; } public DateTime? DueDate { get; set; } public string? Description { get; set; } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Shared.Models { public sealed class UpdateRoles { public string UserId { get; set; } public string[] Roles { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class TeacherService : HttpService<Teacher, Registration>, ITeacherService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public TeacherService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) : base(httpClient, appSettings, configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<Teacher[]> GetAllSignedUpAsync(string? schoolId = null, string[]? include = null) { var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", $"reg/Teachers"); return await _httpClient.GetJsonAsync<Teacher[]>($"{_appSettings.ApiUrl}/{endpoint}{IncludeStringHelper.GetString(include)}SchoolId={schoolId}&returnSignedUpTeachers=true"); } } } <file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IStudentService : IGenericService<Student, Registration> { Task<Student[]> GetAllAsync(string? schoolId = null, string? classId = null, string? parentId = null, string? subject = null, string[]? include = null); } } <file_sep> using FluentValidation; namespace S3.WebUI.cBlazor.Models.Validators { public class ClassSubjectScoresValidator : AbstractValidator<ClassSubjectScores> { public ClassSubjectScoresValidator() { //RuleFor(x => x.ClassId) // .NotEmpty().WithMessage("Class's Id is required."); //RuleFor(x => x.ClassName) // .MaximumLength(20).WithMessage("Class name is too long, maximum of 20 character is allowed."); //RuleFor(x => x.Subject) // .MaximumLength(50).WithMessage("Class name is too long, maximum of 50 character is allowed."); //RuleFor(x => x.ExamType) // .MaximumLength(20).WithMessage("Class name is too long, maximum of 20 character is allowed."); //RuleFor(x => x.Term) // .NotEmpty().WithMessage("Term is required."); //RuleFor(x => x.Session) // .NotEmpty().WithMessage("Session is required."); RuleFor(x => x.StudentScores) .NotNull().WithMessage("Student scores are required."); RuleForEach(x => x.StudentScores).SetValidator(new StudentScoreValidator()); } } } <file_sep>#!/bin/bash cd src/S3.WebUI.cBlazor docker build -t blazor-webui:1.0 .<file_sep> using FluentValidation; using System; namespace S3.WebUI.cBlazor.Models.Validators { public class TeacherValidator : AbstractValidator<Teacher> { public TeacherValidator() { RuleFor(x => x.FirstName) .NotEmpty().WithMessage("First name is required.") .MinimumLength(2).WithMessage("First name is too short.") .MaximumLength(30).WithMessage("First name is too long. Maximum of 30 characters is allowed."); RuleFor(x => x.MiddleName) .MinimumLength(2).When(y => !string.IsNullOrEmpty(y.MiddleName)).WithMessage("Middle name is too short.") .MaximumLength(30).WithMessage("Middle name is too long. Maximum of 30 characters is allowed."); RuleFor(x => x.LastName) .NotEmpty().WithMessage("Last name is required.") .MinimumLength(2).WithMessage("Last name is too short.") .MaximumLength(30).WithMessage("Last name is too long. Maximum of 30 characters is allowed."); RuleFor(x => x.Gender) .NotEmpty().WithMessage("Gender is required."); RuleFor(x => x.DateOfBirth) .LessThanOrEqualTo(DateTime.Now).When(x => !(x.DateOfBirth is null)).WithMessage("Invalid date of birth."); RuleFor(x => x.Email) .EmailAddress().When(y => !string.IsNullOrEmpty(y.Email)).WithMessage("Invalid email address."); RuleFor(x => x.SchoolId) .NotEmpty().WithMessage("School is required."); RuleFor(x => x.Address).SetValidator(new AddressValidator()); } } } <file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface ISchoolService : IGenericService<School, Registration> { Task<SchoolStatistics[]> GetAllStatsAsync(); } } <file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class RuleService : HttpService<Rule, Record>, IRuleService { public RuleService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) : base(httpClient, appSettings, configuration) { } } } <file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IReportService { Task<ClassReport> GetAsync(int session, string? schoolId = null, string? studentId = null, string? classId = null); } } <file_sep> using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class Role { public const string SuperAdmin = "Super Admin"; public const string Admin = "Admin"; public const string SchoolAdmin = "School Admin"; public const string AssistantSchoolAdmin = "Assistant School Admin"; public const string Teacher = "Teacher"; public const string Parent = "Parent"; public const string Student = "Student"; //public string[] AssignableRoles { get; set; } } } <file_sep>using System.Collections.Generic; namespace S3.WebUI.cBlazor.Shared.Models { public class IdentityTokens { public string AccessToken { get; set; } public string RefreshToken { get; set; } public string[] Roles { get; set; } public IDictionary<string, string> Claims { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class MiscellaneousService : IMiscellaneousService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public MiscellaneousService(IConfiguration configuration, HttpClient httpClient, IAuthService authService, AppSettings appSettings) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<bool> CheckUsernameAvailabilityAsync(string username) { var endpoint = _configuration.GetSection("endpoints")["checkUsername"]; return await _httpClient.GetJsonAsync<bool>($"{_appSettings.ApiUrl}/{endpoint}?username={username}"); } public async Task<Address> GetAddressAsync(string addressId) { var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["get"], "variable", $"reg/Addresses"); return await _httpClient.GetJsonAsync<Address>($"{_appSettings.ApiUrl}/{endpoint}/{addressId}"); } } } <file_sep>//using Microsoft.AspNetCore.Components.Builder; //using Microsoft.Extensions.DependencyInjection; //using System; //using System.Net.Http; //using System.Threading.Tasks; //using MatBlazor; //using Microsoft.Extensions.Configuration; //using S3.WebUI.cBlazor.Shared.Config; //using PeterLeslieMorris.Blazor.Validation; //using Blazor.FlexGrid; //using S3.WebUI.cBlazor.Utility; //using System.IO; //using System.Reflection; //using Blazor.FlexGrid.DataSet; //using Microsoft.Extensions.DependencyInjection.Extensions; //using Blazor.FlexGrid.DataSet.Http; //namespace S3.WebUI.cBlazor //{ // public class Startup // { // public void ConfigureServices(IServiceCollection services) // { // services.AddFlexGrid(); // services.AddEnvironmentConfiguration<Startup>(() => // new EnvironmentChooser("Development") // .Add("localhost", "Development") // .Add("xyz.com", "Production", false)); // services.AddFormValidation(config => config.AddFluentValidation(typeof(Startup).Assembly)); // //services.AddSingleton<HttpClient>(); /// Not needed in client side model // services.RegisterShared(); // services.AddMatToaster(config => // { // config.MaximumOpacity = 100; // config.VisibleStateDuration = 7000; // config.HideTransitionDuration = 1000; // }); // services.TryAddScoped(typeof(ILazyDataSetLoader<>), typeof(NullLazyDataSetLoader<>)); // services.TryAddScoped(typeof(ILazyDataSetItemManipulator<>), typeof(NullLazyDataSetItemManipulator<>)); // services.TryAddScoped(typeof(ICreateItemHandle<,>), typeof(NullCreateItemHandler<,>)); // } // public void Configure(IComponentsApplicationBuilder app) // { // //force config initialisation with current uri // IConfiguration config = app.Services.GetService<IConfiguration>(); // app.AddComponent<App>("app"); // } // } //} <file_sep> using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class School : BaseEntity { public string Name { get; set; } public string Category { get; set; } // Primary, Secondary //***TODO: an enumeration might be better public string Email { get; set; } public string PhoneNumber { get; set; } public string AddressId { get; set; } public SchoolAddress Address { get; set; } public virtual ICollection<Teacher> Teachers { get; set; } public virtual ICollection<Class> Classes { get; set; } public virtual ICollection<Student> Students { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class ClassService : HttpService<Class, Registration>, IClassService { public ClassService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) : base(httpClient, appSettings, configuration) { } } } <file_sep>using System.Net.Http; namespace S3.WebUI.cBlazor.Utility { public class Registration { } public class Record { } public class Notification { } } <file_sep># FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build # WORKDIR /src # COPY S3.WebUI.cBlazor.csproj . # RUN dotnet restore "S3.WebUI.cBlazor.csproj" # COPY . . # RUN dotnet build "S3.WebUI.cBlazor.csproj" -c Release -o /app/build # FROM build AS publish # RUN dotnet publish "S3.WebUI.cBlazor.csproj" -c Release -o /app/publish # FROM nginx:alpine AS final # WORKDIR /usr/share/nginx/html # COPY --from=publish /app/publish/S3.WebUI.cBlazor/dist . # COPY nginx.conf /etc/nginx/nginx.conf ################################################## #FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build FROM nginx:alpine AS final ENV ASPNETCORE_ENVIRONMENT docker #Remove default configuration RUN rm /etc/nginx/conf.d/default.conf WORKDIR /usr/share/nginx/html COPY ./bin/Debug/netstandard2.1/dist . COPY nginx.conf /etc/nginx/nginx.conf VOLUME /usr/share/nginx/html VOLUME /etc/nginx ########################################################## #FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base #WORKDIR /app #EXPOSE 80 #EXPOSE 443 # #FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build #WORKDIR /src #COPY ["src/S3.WebUI.cBlazor/S3.WebUI.cBlazor.csproj", "src/S3.WebUI.cBlazor/"] #RUN dotnet restore "src/S3.WebUI.cBlazor/S3.WebUI.cBlazor.csproj" #COPY . . #WORKDIR "/src/src/S3.WebUI.cBlazor" #RUN dotnet build "S3.WebUI.cBlazor.csproj" -c Release -o /app/build # #FROM build AS publish #RUN dotnet publish "S3.WebUI.cBlazor.csproj" -c Release -o /app/publish # #FROM base AS final #WORKDIR /app #COPY --from=publish /app/publish . #ENTRYPOINT ["dotnet", "S3.WebUI.cBlazor.dll"]<file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IParentService : IGenericService<Parent, Registration> { Task<Parent> GetAsync(string regNumber); } } <file_sep> using FluentValidation; using System; namespace S3.WebUI.cBlazor.Models.Validators { public class ClassValidator : AbstractValidator<Class> { public ClassValidator() { RuleFor(x => x.SchoolId) .NotEmpty().WithMessage("School's Id is required."); RuleFor(x => x.Name) .NotEmpty().WithMessage("Name is required.") .MinimumLength(2).WithMessage("Name is too short.") .MaximumLength(20).WithMessage("Name is too long. Maximum of 20 characters is allowed."); RuleFor(x => x.Category) .NotEmpty().WithMessage("Category is required."); RuleFor(x => x.SubjectsArray) .NotEmpty().WithMessage("Supply the subjects offered in this class."); } } } <file_sep>#!/bin/bash export ASPNETCORE_ENVIRONMENT=local cd src/S3.WebUI.cBlazor dotnet run --no-restore<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Models { public class StudentScore : BaseEntity { public string StudentId { get; set; } public string StudentName { get; set; } public string SchoolId { get; set; } public string ClassId { get; set; } public string ClassName { get; set; } public string Subject { get; set; } public string ExamType { get; set; } // CA, First Exam, Second Exam, Homework, Class Activities public string Term { get; set; } public int Session { get; set; } public float? Mark { get; set; } // Make mark nullable, so that zero does not get displayed in the UI control by default public string RuleId { get; set; } // The rule to be used to determine the weight of this score and grade obtained in this subject } }<file_sep> using Blazor.FlexGrid.Components.Configuration; using Blazor.FlexGrid.Components.Configuration.Builders; namespace S3.WebUI.cBlazor.Models.GridDisplayConfigurations { public class SchoolStatisticsGridConfiguration : IEntityTypeConfiguration<SchoolStatistics> { public void Configure(EntityTypeBuilder<SchoolStatistics> builder) { //builder.HasEmptyItemsMessage("<h1>Test</h1>"); builder.Property(x => x.Name).HasOrder(1).HasCaption("School Name").IsSortable().IsFilterable(); builder.Property(x => x.Category).HasOrder(2).IsSortable().IsFilterable(); builder.Property(x => x.Location).HasOrder(3).IsSortable().IsFilterable(); builder.Property(x => x.NumberOfClasses).HasOrder(4).HasCaption("Classes").IsSortable(); builder.Property(x => x.NumberOfStudents).HasOrder(5).HasCaption("Students").IsSortable(); builder.Property(x => x.NumberOfTeachers).HasOrder(6).HasCaption("Teachers").IsSortable(); builder.Property(x => x.Administrator).HasOrder(7); builder.Property(x => x.PhoneNumber).HasOrder(8).HasCaption("Phone"); //builder.Property(x => x.Id).IsVisible(false); builder.Property(x => x.AdministratorId).IsVisible(false); builder.Property(x => x.CreatedDate).IsVisible(false); builder.Property(x => x.UpdatedDate).IsVisible(false); builder.Property(x => x.Email).IsVisible(false); } } }<file_sep>using System.Threading.Tasks; using Blazored.LocalStorage; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services.Interface; namespace S3.WebUI.cBlazor.Shared.Services { public class AuthService : IAuthService { private readonly ILocalStorageService _storage; private const string IdentityTokensKey = "identity_token"; public AuthService(ILocalStorageService storage) => _storage = storage; public async Task<IdentityTokens> GetIdentityTokensAsync() => await _storage.GetItemAsync<IdentityTokens>(IdentityTokensKey); public async Task SetIdentityTokensAsync(IdentityTokens identityTokens) => await _storage.SetItemAsync(IdentityTokensKey, identityTokens); public async Task RemoveIdentityTokensAsync() => await _storage.RemoveItemAsync(IdentityTokensKey); } } <file_sep>using System; using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class Parent : Person { public string RegNumber { get; } public string? AddressId { get; set; } public string[] StudentIds { get; set; } // List of wards public virtual ParentAddress Address { get; set; } public virtual ICollection<Student> Students { get; set; } } } <file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class ScoresEntryTaskService : HttpService<ScoresEntryTask, Registration>, IScoresEntryTaskService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public ScoresEntryTaskService(IConfiguration configuration, HttpClient httpClient, AppSettings appSettings) : base(httpClient, appSettings, configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<ScoresEntryTask[]> GetAllForTeacherAsync(string teacherId, string? schoolId = null, string[]? include = null) { var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", $"reg/ScoresEntryTasks"); return await _httpClient.GetJsonAsync<ScoresEntryTask[]>($"{_appSettings.ApiUrl}/{endpoint}{IncludeStringHelper.GetString(include)}SchoolId={schoolId}&TeacherId={teacherId}"); } } } <file_sep>using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IScoresEntryTaskService : IGenericService<ScoresEntryTask, Registration> { Task<ScoresEntryTask[]> GetAllForTeacherAsync(string teacherId, string? schoolId = null, string[]? include = null); } } <file_sep>using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Shared.Models { public sealed class SignUp { public string UserId { get; set; } public string Username { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } public string[] Roles { get; set; } public string SchoolId { get; set; } } }<file_sep>#!/bin/bash dotnet publish ./src/S3.WebUI.cBlazor -c Release --no-build --no-restore -o ./bin/Release/netstandard2.0<file_sep>using System; namespace S3.WebUI.cBlazor.Models { public class Person : BaseEntity { public string FirstName { get; set; } public string? MiddleName { get; set; } public string LastName { get; set; } public string FullName { get => FirstName + " " + MiddleName + " " + LastName; } public string Gender { get; set; } public string? PhoneNumber { get; set; } public string? Email { get; set; } public DateTime? DateOfBirth { get; set; } public bool IsSignedUp { get; set; } public string[] RolesArray { get; set; } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Shared.Models { public sealed class ChangePassword { public string UserId { get; set; } public string CurrentPassword { get; set; } public string NewPassword { get; set; } public string ConfirmPassword { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IStudentScoreService//// : IGenericService<StudentScore, Record> { Task<StudentScore> GetAsync(string id, string[]? include = null); Task<StudentScore[]> GetAllAsync(string? schoolId = null, string? studentId = null, string? classId = null, string? subject = null, string? examType = null, string? term = null, int? session = null, string[]? include = null); Task CreateAsync(ClassSubjectScores classSubjectScores); Task UpdateAsync(ClassSubjectScores classSubjectScores); Task DeleteAsync(string id); } } <file_sep>using System; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; namespace S3.WebUI.cBlazor.Shared.Services { public abstract class HttpService<T, N> : IGenericService<T, N> // T = type, N = External Service Name { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; protected HttpService(HttpClient httpClient, AppSettings appSettings, IConfiguration configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<T> GetAsync(string id, string[] include = null) => await _httpClient.GetJsonAsync<T>($"{_appSettings.ApiUrl}/{GetEndPoint("get", typeof(T), typeof(N))}/{id}{IncludeStringHelper.GetString(include)}"); public async Task<T[]> GetAllAsync(string? schoolId = null, string[]? include = null) => await _httpClient.GetJsonAsync<T[]>($"{_appSettings.ApiUrl}/{GetEndPoint("getAll", typeof(T), typeof(N))}{IncludeStringHelper.GetString(include)}SchoolId={schoolId}"); public async Task CreateAsync(T t) => await CreateHttpRequestAsync(http => http.PostJsonAsync($"{_appSettings.ApiUrl}/{GetEndPoint("create", typeof(T), typeof(N))}", t)); public async Task UpdateAsync(T t) => CreateHttpRequestAsync(http => http.PutJsonAsync($"{_appSettings.ApiUrl}/{GetEndPoint("update", typeof(T), typeof(N))}", t)); public async Task DeleteAsync(string id) => CreateHttpRequestAsync(http => http.DeleteAsync($"{_appSettings.ApiUrl}/{GetEndPoint("delete", typeof(T), typeof(N))}/{id}")); private async Task CreateHttpRequestAsync(Func<HttpClient, Task> request, bool authorized = true) => await request(_httpClient); private string GetEndPoint(string endPointName, Type type, Type serviceName) { string typeName = type.Name.EndsWith("s") ? $"{type.Name}es" : type.Name.EndsWith("y") ? $"{type.Name.Substring(0, type.Name.Length - 1)}ies" : $"{type.Name}s"; //string typeName = type.Name.EndsWith('s') ? $"{type.Name}es" : // type.Name.EndsWith('y') ? // $"{type.Name[0..^1]}ies" : // $"{type.Name}s"; string servicePrefix = serviceName.Name switch { "Registration" => "reg", "Record" => "rec", "Notification" => "notif", _ => "" }; return Regex.Replace(_configuration.GetSection("endpoints")[endPointName], "variable", $"{servicePrefix}/{typeName}"); } } } //using System; //using System.IO; //using System.Linq; //using System.Net.Http; //using System.Net.Http.Headers; //using System.Threading.Tasks; //using Microsoft.AspNetCore.Blazor; //using Microsoft.AspNetCore.Components; //using S3.WebUI.cBlazor.Shared.Models; //using S3.WebUI.cBlazor.Shared.Services.Interface; //namespace S3.WebUI.cBlazor.Shared.Services //{ // public abstract class HttpService // { // private readonly HttpClient _httpClient; // private readonly IAuthService _authService; // private readonly AppSettings _settings; // protected HttpService(HttpClient httpClient, IAuthService authService, AppSettings settings) // { // _httpClient = httpClient; // _authService = authService; // _settings = settings; // } // protected async Task<TResult> GetAsync<TResult>(string endpoint, bool authorized = true) // => await _httpClient.GetJsonAsync<TResult>($"{_settings.ApiUrl}/{endpoint}"); // protected Task PostAsync(string endpoint, object content, bool authorized = true) // => CreateHttpRequestAsync(http => http.PostJsonAsync($"{_settings.ApiUrl}/{endpoint}", content), authorized); // protected async Task<TResult> PostAsync<TResult>(string endpoint, object content, bool authorized = true) // => await _httpClient.PostJsonAsync<TResult>($"{_settings.ApiUrl}/{endpoint}", content); // protected Task PutAsync(string endpoint, object content, bool authorized = true) // => CreateHttpRequestAsync(http => http.PutJsonAsync($"{_settings.ApiUrl}/{endpoint}", content), authorized); // protected Task DeleteAsync(string endpoint, bool authorized = true) // => CreateHttpRequestAsync(http => http.DeleteAsync($"{_settings.ApiUrl}/{endpoint}"), authorized); // private async Task CreateHttpRequestAsync(Func<HttpClient, Task> request, bool authorized = true) // => await request(_httpClient); // } //}<file_sep>using System; using System.Collections.Generic; namespace S3.WebUI.cBlazor.Models { public class Teacher : Person { public string? Position { get; set; } public int? GradeLevel { get; set; } public int? Step { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public string? AddressId { get; set; } public virtual TeacherAddress Address { get; set; } public virtual ICollection<ScoresEntryTask> ScoresEntryTasks { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class StudentScoreService : IStudentScoreService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public StudentScoreService(IConfiguration configuration, HttpClient httpClient, IAuthService authService, AppSettings appSettings) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task CreateAsync(ClassSubjectScores classSubjectScores) => await _httpClient.PostJsonAsync($"{_appSettings.ApiUrl}/{GetEndPoint("create")}", classSubjectScores); public async Task DeleteAsync(string id) => await _httpClient.DeleteAsync($"{_appSettings.ApiUrl}/{GetEndPoint("delete")}/{id}"); public async Task<StudentScore[]> GetAllAsync(string? schoolId = null, string? studentId = null, string? classId = null, string? subject = null, string? examType = null, string? term = null, int? session = null, string[]? include = null) => await _httpClient.GetJsonAsync<StudentScore[]>($"{_appSettings.ApiUrl}/{GetEndPoint("getAll")}" + $"{IncludeStringHelper.GetString(include)}schoolId={schoolId}&studentId={studentId}&classId={classId}&subject={subject}" + $"&examType={examType}&term={term}&session={session}"); public async Task<StudentScore> GetAsync(string id, string[]? include = null) => await _httpClient.GetJsonAsync<StudentScore>($"{_appSettings.ApiUrl}/{GetEndPoint("get")}/{id}{IncludeStringHelper.GetString(include)}"); public async Task UpdateAsync(ClassSubjectScores classSubjectScores) => await _httpClient.PutJsonAsync($"{_appSettings.ApiUrl}/{GetEndPoint("update")}", classSubjectScores); private string GetEndPoint(string endPointName) => Regex.Replace(_configuration.GetSection("endpoints")[endPointName], "variable", $"rec/StudentScores"); //public async Task<Student[]> GetAllAsync(string parentId, string? schoolId = null, string[]? include = null) //{ // var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", $"reg/Students"); // return await _httpClient.GetJsonAsync<Student[]>($"{_appSettings.ApiUrl}/{endpoint}{IncludeStringHelper.GetString(include)}SchoolId={schoolId}&ParentId={parentId}"); //} } } <file_sep> using System; using System.Text.RegularExpressions; using FluentValidation; namespace S3.WebUI.cBlazor.Shared.Models.Validators { public class SignInValidator : AbstractValidator<SignIn> { public SignInValidator() { RuleFor(x => x.Username) .NotEmpty().WithMessage("Username is required."); RuleFor(x => x.Password) .NotEmpty().WithMessage("Password is required."); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Models { public class ClassSubjectScores : BaseEntity { public List<StudentScore> StudentScores { get; set; } } } <file_sep>using System.IO; using System.Reflection; using System.Text.Json; using Blazored.LocalStorage; using Microsoft.Extensions.DependencyInjection; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using Microsoft.Extensions.DependencyInjection.Extensions; using S3.WebUI.cBlazor.Shared.Services.Interface; using Blazor.FlexGrid; using Blazor.FlexGrid.DataSet; using Blazor.FlexGrid.DataSet.Http; using S3.WebUI.cBlazor.Models.GridDisplayConfigurations; using S3.WebUI.cBlazor.Utility; using System; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Linq; using MatBlazor; using Microsoft.Extensions.Configuration.Json; using Microsoft.AspNetCore.Components; using PeterLeslieMorris.Blazor.Validation; namespace S3.WebUI.cBlazor.Shared.Config { public static class Extensions { public static IServiceCollection RegisterShared(this IServiceCollection services) { //services.AddFlexGridServerSide(cfg => //{ // cfg.ApplyConfiguration(new SchoolStatisticsGridConfiguration()); //}); services.AddFlexGrid(); //services.TryAddScoped(typeof(ILazyDataSetLoader<>), typeof(NullLazyDataSetLoader<>)); //services.TryAddScoped(typeof(ILazyDataSetItemManipulator<>), typeof(NullLazyDataSetItemManipulator<>)); //services.TryAddScoped(typeof(ICreateItemHandle<,>), typeof(NullCreateItemHandler<,>)); services.AddFormValidation(config => config.AddFluentValidation(typeof(Program).Assembly)); services.AddBlazoredLocalStorage(); services.AddSingleton(GetAppSettings()); services.AddScoped<AppUser>(); services.AddScoped<IAuthService, AuthService>(); services.AddScoped<IIdentityService, IdentityService>(); services.AddScoped<IStudentService, StudentService>(); services.AddScoped<IClassService, ClassService>(); services.AddScoped<IParentService, ParentService>(); services.AddScoped<ITeacherService, TeacherService>(); services.AddScoped<ISchoolService, SchoolService>(); services.AddScoped<IStudentScoreService, StudentScoreService>(); services.AddScoped<IScoresEntryTaskService, ScoresEntryTaskService>(); services.AddScoped<IRuleService, RuleService>(); services.AddScoped<IReportService, ReportService>(); services.AddScoped<IMiscellaneousService, MiscellaneousService>(); services.AddMatToaster(config => { config.MaximumOpacity = 100; config.VisibleStateDuration = 7000; config.HideTransitionDuration = 1000; }); return services; } private static AppSettings GetAppSettings() { using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"); using var reader = new StreamReader(stream); return JsonSerializer.Deserialize<AppSettings>(reader.ReadToEnd(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Models { public class Score : BaseEntity { public string StudentId { get; set; } public string StudentName { get; set; } public float Mark { get; set; } public string ClassSubjectScoresId { get; set; } public virtual ClassSubjectScores ClassSubjectScores { get; set; } } } <file_sep>using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface ITeacherService : IGenericService<Teacher, Registration> { Task<Teacher[]> GetAllSignedUpAsync(string? schoolId = null, string[]? include = null); } } <file_sep>using System.Net.Http; namespace S3.WebUI.cBlazor.Utility { public class ErrorMessageHelper { public static (string, string, bool) GetMessage(HttpRequestException ex) { string errorTitle; string errorMessage; bool sessionExpired = false; if (ex.Message.Contains("400")) //400 (Bad Request). { errorTitle = "Bad Request"; errorMessage = "One of the specified input was not valid."; } else if (ex.Message.Contains("401")) //401 (Unauthorized). { errorTitle = "Session Expired"; errorMessage = "Your session has expired. Please, login again."; sessionExpired = true; } else if (ex.Message.Contains("403")) //403 (Forbidden). { errorTitle = "Access Denied"; errorMessage = "You are not authorised to view this resource. Please, contact the administrator."; } else if (ex.Message.Contains("404")) //404 (Not Found). { errorTitle = "Not Found"; errorMessage = "Nothing found for the specified input."; } else if (ex.Message.Contains("500")) // 500 (Internal Server Error). { errorTitle = "Service Unvailable"; errorMessage = "A required service is temporarily unavailable. Please, try again later."; } else // (Unknown Error). { errorTitle = "Error"; errorMessage = "Sorry, we could not load this resource due to an error. Please, try again later."; } return (errorTitle, errorMessage, sessionExpired); } } } <file_sep>using System; namespace S3.WebUI.cBlazor.Models { public class Student : Person { public string RegNumber { get; } public string SubjectsStatus { get; set; } public string[] SubjectsArray { get; set; } public bool OfferingAllClassSubjects { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public string? ClassId { get; set; } public virtual Class Class { get; set; } public string? ParentId { get; set; } public virtual Parent Parent { get; set; } public string? AddressId { get; set; } public virtual StudentAddress Address { get; set; } } } <file_sep> using System; using System.Text.RegularExpressions; using FluentValidation; namespace S3.WebUI.cBlazor.Shared.Models.Validators { public class ResetPasswordValidator : AbstractValidator<ResetPassword> { public ResetPasswordValidator() { RuleFor(x => x.UserId) .NotEmpty().WithMessage("User's Id is required."); RuleFor(x => x.Password) .NotEmpty().WithMessage("Password is required.") .MinimumLength(6).When(y => !string.IsNullOrEmpty(y.Password)).WithMessage("Password is too short. Minimum of 6 characters is allowed.") .MaximumLength(50).WithMessage("Password is too long. Maximum of 50 characters is allowed.") .Must(password => ValidatePassword(password)).When(y => !string.IsNullOrEmpty(y.Password)).WithMessage("Password must contain upper case, lower case, number and symbol."); RuleFor(x => x.ConfirmPassword) .NotEmpty().WithMessage("Password confirmation is required.") .Equal(x => x.Password).When(y => !string.IsNullOrEmpty(y.ConfirmPassword)).WithMessage("Password and Confirm Password do not match."); } private bool ValidatePassword(string password) { var hasNumber = new Regex(@"[0-9]+"); var hasUpperChar = new Regex(@"[A-Z]+"); var hasLowerChar = new Regex(@"[a-z]+"); var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]"); if (!hasLowerChar.IsMatch(password)) { return false; } if (!hasUpperChar.IsMatch(password)) { return false; } if (!hasNumber.IsMatch(password)) { return false; } if (!hasSymbols.IsMatch(password)) { return false; } return true; } } } <file_sep>using Blazored.LocalStorage; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Models { public class AppUser { private readonly IAuthService _authService; private readonly IIdentityService _identityService; private readonly HttpClient _httpClient; public string Id { get; private set; } public string Username { get; private set; } public string SchoolId { get; private set; } public bool IsSignedIn { get; private set; } public bool IsSuperAdmin { get; private set; } public bool IsAdmin { get; private set; } public bool IsSchoolAdmin { get; private set; } public bool IsAssistantSchoolAdmin { get; private set; } public bool IsTeacher { get; private set; } public bool IsParent { get; private set; } public bool IsStudent { get; private set; } public AppUser(IAuthService authService, IIdentityService identityService, HttpClient httpClient) => (_authService, _httpClient, _identityService) = (authService, httpClient, identityService); public async Task InitializeAsync() { var identityTokens = await _authService.GetIdentityTokensAsync(); if (!(identityTokens is null)) { SetAuthorizationHeader(isSignedIn: true, identityTokens.AccessToken); SetUserPermissions(isSignedIn: true, identityTokens: identityTokens); SetUserRoles(identityTokens.Roles); } else { SetAuthorizationHeader(isSignedIn: false); SetUserPermissions(isSignedIn: false); } } public async Task SingInAsycn(SignIn signIn) { var identityTokens = await _identityService.SignInAsync(signIn); if (!(identityTokens is null)) { await SaveIdentityTokensAsync(identityTokens); SetAuthorizationHeader(isSignedIn: true, identityTokens.AccessToken); SetUserPermissions(isSignedIn: true, identityTokens: identityTokens); SetUserRoles(identityTokens.Roles); } } public async Task SignOutAsync() { await RemoveIdentityTokensAsync(); SetAuthorizationHeader(isSignedIn: false); SetUserPermissions(isSignedIn: false); } private async Task SaveIdentityTokensAsync(IdentityTokens identityTokens) => await _authService.SetIdentityTokensAsync(identityTokens); private void SetAuthorizationHeader(bool isSignedIn, string accessToken = "") { if (isSignedIn && !_httpClient.DefaultRequestHeaders.Contains("Authorization")) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } else if(!isSignedIn) { _httpClient.DefaultRequestHeaders.Authorization = null; } } private async Task RemoveIdentityTokensAsync() => await _authService.RemoveIdentityTokensAsync(); private void SetUserPermissions(bool isSignedIn, IdentityTokens identityTokens = null) { if (isSignedIn) { IsSignedIn = true; Id = identityTokens.Claims["id"]; Username = identityTokens.Claims["username"]; SchoolId = identityTokens.Claims["schoolId"]; } else { Id = string.Empty; Username = string.Empty; SchoolId = string.Empty; IsSignedIn = false; IsSuperAdmin = false; IsAdmin = false; IsSchoolAdmin = false; IsAssistantSchoolAdmin = false; IsTeacher = false; IsParent = false; IsStudent = false; } } private void SetUserRoles(string[] roles) { foreach (var role in roles) { // Use pattern matching _ = role switch { Role.SuperAdmin => IsSuperAdmin = true, Role.Admin => IsAdmin = true, Role.SchoolAdmin => IsSchoolAdmin = true, Role.AssistantSchoolAdmin => IsAssistantSchoolAdmin = true, Role.Teacher => IsTeacher = true, Role.Parent => IsParent = true, Role.Student => IsStudent = true, _ => IsSignedIn = false // Invalid role found, log the user out }; } } } } //using Blazored.LocalStorage; //using S3.WebUI.cBlazor.Shared.Services; //using S3.WebUI.cBlazor.Shared.Services.Interface; //using System; //using System.Net.Http; //using System.Net.Http.Headers; //using System.Threading.Tasks; //namespace S3.WebUI.cBlazor.Shared.Models //{ // public class User // { // private readonly IAuthService _authService; // private readonly IIdentityService _identityService; // private readonly HttpClient _httpClient; // public bool IsLoggedIn { get; private set; } // public User(IAuthService authService, IIdentityService identityService, HttpClient httpClient) // => (_authService, _httpClient, _identityService) = (authService, httpClient, identityService); // public async Task InitializeAsync() // { // var accessToken = await _authService.GetAccessTokenAsync(); // if (!string.IsNullOrEmpty(accessToken)) // { // SetAuthorizationHeader(accessToken); // IsLoggedIn = true; // } // } // public async Task SingInAsycn(Identity identity) // { // var tokens = await _identityService.SignInAsync(identity); // if (!(tokens is null)) // { // await SaveAccessTokenAsync(tokens.AccessToken); // SetAuthorizationHeader(tokens.AccessToken); // IsLoggedIn = true; // } // } // public async Task SignOutAsync() // { // await RemoveAccessTokenAsync(); // _httpClient.DefaultRequestHeaders.Authorization = null; // IsLoggedIn = false; // } // private async Task SaveAccessTokenAsync(string accessToken) // => await _authService.SetAccessTokenAsync(accessToken); // private void SetAuthorizationHeader(string accessToken) // { // if (!_httpClient.DefaultRequestHeaders.Contains("Authorization")) // _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // } // private async Task RemoveAccessTokenAsync() // => await _authService.RemoveAccessTokenAsync(); // } //}<file_sep> //namespace S3.WebUI.cBlazor.Models //{ // public class Country // { // public string[] Countries { get; set; } // } //} <file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IGenericService<T, N> // T = type, N = External Service Name { Task<T> GetAsync(string id, string[]? include = null); Task<T[]> GetAllAsync(string? schoolId = null, string[]? include = null); Task CreateAsync(T t); Task UpdateAsync(T t); Task DeleteAsync(string id); } } <file_sep>using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Shared.Models { public sealed class ResetPassword { public string UserId { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } } }<file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class StudentService : HttpService<Student, Registration>, IStudentService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public StudentService(IConfiguration configuration, HttpClient httpClient, IAuthService authService, AppSettings appSettings) : base(httpClient, appSettings, configuration) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<Student[]> GetAllAsync(string? schoolId = null, string? classId = null, string? parentId = null, string? subject = null, string[]? include = null) { var endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", $"reg/Students"); return await _httpClient.GetJsonAsync<Student[]>($"{_appSettings.ApiUrl}/{endpoint}" + $"{IncludeStringHelper.GetString(include)}" + $"schoolId={schoolId}&classId={classId}&parentId={parentId}&subject={subject}"); } } } //using Microsoft.AspNetCore.Components; //using Microsoft.Extensions.Configuration; ////using Newtonsoft.Json; ////using Newtonsoft.Json.Serialization; //using S3.WebUI.cBlazor.Models; //using System; //using System.Collections.Generic; //using System.Linq; //using System.Net.Http; //using System.Text.Json; //using System.Text.RegularExpressions; //using System.Threading.Tasks; ////using JsonSerializer = Newtonsoft.Json.JsonSerializer; ////using JsonSerializer = System.Text.Json.JsonSerializer; //namespace S3.WebUI.cBlazor.Areas.SchoolAdmin.Services //{ // //public class StudentService : HttpService, IStudentService // public class StudentService : IStudentService // { // private readonly HttpClient _httpClient; // private readonly IConfiguration _configuration; // public StudentService(HttpClient httpClient, IConfiguration configuration) // => (_httpClient, _configuration) = (httpClient, configuration); // public async Task<Student> GetAsync(Guid id) // { // string endpoint = Regex.Replace(_configuration.GetSection("endpoints")["get"], "variable", "students"); // return await _httpClient.GetJsonAsync<Student>($"{endpoint}/{id}"); // } // public async Task<Student[]> GetAllAsync(Guid? schoolId = null) // { // string endpoint = Regex.Replace(_configuration.GetSection("endpoints")["getAll"], "variable", "students"); // return await _httpClient.GetJsonAsync<Student[]>($"{endpoint}?SchoolId={schoolId}"); // } // public async Task CreateAsync(Student student) // { // string endpoint = Regex.Replace(_configuration.GetSection("endpoints")["create"], "variable", "students"); // System.Diagnostics.Debug.WriteLine( // JsonSerializer.Serialize(student, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); // await _httpClient.SendJsonAsync(HttpMethod.Post, endpoint, student); // } // public async Task UpdateAsync(Student student) // { // string endpoint = Regex.Replace(_configuration.GetSection("endpoints")["update"], "variable", "students"); // await _httpClient.SendJsonAsync(HttpMethod.Put, endpoint, student); // } // public async Task DeleteAsync(Guid id) // { // string endpoint = Regex.Replace(_configuration.GetSection("endpoints")["delete"], "variable", "students"); // await _httpClient.SendJsonAsync(HttpMethod.Delete, $"{endpoint}/{id}", null); // } // } //} <file_sep>using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Configuration; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Shared.Models; using S3.WebUI.cBlazor.Shared.Services; using S3.WebUI.cBlazor.Shared.Services.Interface; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services { public class ReportService : IReportService { private readonly HttpClient _httpClient; private readonly AppSettings _appSettings; private readonly IConfiguration _configuration; public ReportService(IConfiguration configuration, HttpClient httpClient, IAuthService authService, AppSettings appSettings) => (_httpClient, _appSettings, _configuration) = (httpClient, appSettings, configuration); public async Task<ClassReport> GetAsync(int session, string? schoolId = null, string? studentId = null, string? classId = null) => await _httpClient.GetJsonAsync<ClassReport>($"{_appSettings.ApiUrl}/{GetEndPoint("get")}" + $"?schoolId={schoolId}&studentId={studentId}&classId={classId}&session={session}"); private string GetEndPoint(string endPointName) => Regex.Replace(_configuration.GetSection("endpoints")[endPointName], "variable", $"rec/ClassReports"); } } <file_sep>using Microsoft.AspNetCore.Components; using S3.WebUI.cBlazor.Models; using S3.WebUI.cBlazor.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace S3.WebUI.cBlazor.Shared.Services.Interface { public interface IMiscellaneousService { Task<Address> GetAddressAsync(string addressId); Task<bool> CheckUsernameAvailabilityAsync(string username); } } <file_sep> using FluentValidation; using System; namespace S3.WebUI.cBlazor.Models.Validators { public class ScoresEntryTaskValidator : AbstractValidator<ScoresEntryTask> { public ScoresEntryTaskValidator() { RuleFor(x => x.SchoolId) .NotEmpty().WithMessage("School's Id is required."); RuleFor(x => x.TeacherId) .NotEmpty().WithMessage("Teacher is required."); RuleFor(x => x.TeacherName) .MaximumLength(100).WithMessage("Teacher's name is too long, maximum of 100 characters is allowed."); RuleFor(x => x.ClassId) .NotEmpty().WithMessage("Class is required."); RuleFor(x => x.ClassName) .MaximumLength(20).WithMessage("Class' name is too long, maximum of 20 characters is allowed."); RuleFor(x => x.DueDate) .GreaterThanOrEqualTo(DateTime.Now).When(x => !(x.DueDate is null)).WithMessage("Invalid due date."); RuleFor(x => x.RuleId) .NotEmpty().WithMessage("Rule is required."); } } } <file_sep>using System.Net.Http; using System.Text; namespace S3.WebUI.cBlazor.Utility { public class IncludeStringHelper { public static string GetString(string[]? include) { StringBuilder includeString = new StringBuilder("?"); if (!(include is null) && include.Length > 0) { foreach (var includeItem in include) { includeString.Append($"include={includeItem}&"); } } return includeString.ToString(); } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace S3.WebUI.cBlazor.Models { public class Rule : BaseEntity { public string SchoolId { get; set; } public string Name { get; set; } public decimal? CAPercentage { get; set; } // Using decimal? (instead of float) because MatNumericUpDownField (binds to decimal?) is the only available UI component which can handle data binding to numeric type public decimal? FirstExamPercentage { get; set; } // Only first exam is compulsory public decimal? SecondExamPercentage { get; set; } public decimal? HomeworkPercentage { get; set; } public decimal? ClassActivitiesPercentage { get; set; } public decimal? A_DistinctionCutoff { get; set; } // e.g. 85 and above public decimal? B_VeryGoodCutoff { get; set; } // e.g. 70 - 84 public decimal? C_CreditCutoff { get; set; } // e.g. 55 - 69 public decimal? P_PassCutoff { get; set; } // e.g. 50 - 54 public decimal? F_FailCutoff { get; set; } // e.g. 0 - 49 public bool IsDefault { get; set; } } }
053c0921cd8025f7c4a7608400ec195069c8305c
[ "JavaScript", "C#", "Dockerfile", "Shell" ]
72
C#
abibtj/LNX-S3.WebUI.cBlazor
d6b70be359cf72a5a0c69d08280b9ad411b280f6
5f256c85ccc73cca8c80f3fee71cab86b7c94249
refs/heads/master
<repo_name>geeeero/npb-cens<file_sep>/survobject.R # what are Surv objects? library(survival) ?Surv test <- Surv(skrpd$time, skrpd$cens) test attributes(test) test2 <- unclass(test) test2 # matrix with first column time and second column event indicator (0 = censored, 1 = failed) # and attribute "type" = "right". # column names are "time" and "status" test3 <- sort(test) # seems to sort Surv objects properly unclass(test3) #<file_sep>/skrp-example.R # using SKPR data & expert knowledge for drive side ball bearing of the suction press source("setup.R") # field data: bearing lifetime in days skrpfielddata <- read.csv("SKRP_DriveSideBearingSuctionPressDATA.csv", sep=";", header=FALSE, colClasses = c("NULL", "numeric", "NULL", "factor"), skip=4) names(skrpfielddata) <- c("time", "cens") skrpfielddata$cens <- as.numeric(skrpfielddata$cens == "Uncensored") skrpfielddata <- skrpfielddata[order(skrpfielddata$time),] skrpd <- data.frame(skrpfielddata, rank=rank(skrpfielddata$time)) #pdf(width=5, height=5, "skrpdata1.pdf") qplot(data=skrpd, x=rank, ymin=rep(0,14), y=time, ymax=time, label=time, vjust=-0.5, geom=c("pointrange", "text"), shape=factor(cens)) + coord_flip() + scale_x_reverse() + scale_shape_manual(values=c(1, 19), label=c("No", "Yes"), name="Failure") #dev.off() # expert info: bearing lifetime in years skrpexpert <- read.csv("SKRP_DriveSideBearingSuctionPressEXPERT.csv", sep=";", header=FALSE, colClasses = c("numeric", "numeric", "numeric", rep("NULL", 17)), skip=3, dec=",") names(skrpexpert) <- c("timel", "timeu", "freq") g <- ggplot(data=skrpexpert) g + geom_bar(aes(x=timeu, y=freq), stat="identity") skrpetimes <- (skrpexpert$timel + skrpexpert$timeu)/2 skrpe <- data.frame(Time=rep(skrpetimes, times=skrpexpert$freq)) #pdf(width=5, height=5, "skrpexpt1.pdf") ggplot(skrpe, aes(x=Time)) + geom_histogram(breaks=seq(0, 10, by=0.5)) #dev.off() # transform into days skrpexpert$timel <- skrpexpert$timel * 365 skrpexpert$timeu <- skrpexpert$timeu * 365 g <- ggplot(data=skrpexpert, aes(x=timeu, y=1-cumsum(freq)/100)) g + geom_step(direction="vh") + geom_step(direction="hv") # reliability values from freq skrpexpert <- data.frame(skrpexpert, rel = 1-cumsum(skrpexpert$freq)/100) skrpe2 <- data.frame(Time=c(0, skrpexpert$timeu), rell=c(skrpexpert$rel, 0), relu=c(1, skrpexpert$rel)) skrpe2 <- skrpe2[-21,] # time grid interval: 18.25 days, such that 10 years = 200 time points e3t <- seq(0, 3650, by=18.25) e3nL <- data.frame(Bearing = rep(14, 201)) e3nU <- data.frame(Bearing = rep(100, 201)) e3yL <- data.frame(Bearing = c(rep(skrpe2$rell, each=10), 0)) e3yU <- data.frame(Bearing = c(rep(skrpe2$relu, each=10), 0.01)) #ggplot() + geom_line(aes(x=e3t, y=e3yL$Bearing)) + geom_line(aes(x=e3t, y=e3yU$Bearing)) e3yL <- not01(e3yL) e3yU <- not01(e3yU) # 'upper', optimistic data: censored bearings continue to function uncens <- skrpfielddata$time[skrpfielddata$cens == 1] udata <- c(uncens, rep(max(e3t)+1, dim(skrpfielddata)[1] - length(uncens))) # 'lower', pessimistic data: censoring times are actually failure times e3dL <- list(Bearing = skrpfielddata$time) e3dU <- list(Bearing = udata) e3resL <- oneCompPriorPostSet("Bearing", e3t, e3dL, e3nL, e3nU, e3yL, e3yU) e3resU <- oneCompPriorPostSet("Bearing", e3t, e3dU, e3nL, e3nU, e3yL, e3yU) e3df <- data.frame( e3resL[,-match("Upper", names(e3resL))], # take out Upper from result with lower data Upper=e3resU[, match("Upper", names(e3resU))]) # add Upper from result with upper data priopostcolours1 <- scale_fill_manual(values = c(tuegreen, tuedarkblue)) priopostcolours2 <- scale_colour_manual(values = c(tuegreen, tuedarkblue)) e3plot <- ggplot(e3df, aes(x=Time)) + priopostcolours1 + priopostcolours2 e3plot <- e3plot + geom_line(aes(y=Upper, group=Item, colour=Item)) + geom_line(aes(y=Lower, group=Item, colour=Item)) e3plot <- e3plot + geom_ribbon(aes(ymin=Lower, ymax=Upper, group=Item, colour=Item, fill=Item), alpha=0.5) e3plot <- e3plot + xlab("Days") + ylab("Survival Probability") + bottomlegend + scale_x_continuous(breaks=(0:10)*365) e3plot #e3plot + coord_cartesian(xlim=c(0,500), ylim=c(0.5,1)) #pdf(width=10, height=5, "skrpcens1.pdf") #e3plot #dev.off() #<file_sep>/setup.R #install.packages("devtools") #library("devtools") #install_github("louisaslett/ReliabilityTheory") library("ReliabilityTheory") library(ggplot2) library(reshape2) library(RColorBrewer) library(xtable) #setwd("../npb-cens") bottomlegend <- theme(legend.position = 'bottom', legend.direction = 'horizontal', legend.title = element_blank()) rightlegend <- theme(legend.title = element_blank()) tuered <- rgb(0.839,0.000,0.290) tueblue <- rgb(0.000,0.400,0.800) tueyellow <- rgb(1.000,0.867,0.000) tuegreen <- rgb(0.000,0.675,0.510) tuewarmred <- rgb(0.969,0.192,0.192) tueorange <- rgb(1.000,0.604,0.000) tuedarkblue <- rgb(0.063,0.063,0.451) # produces survival signature matrix for one component of type "name", # for use in nonParBayesSystemInference() oneCompSurvSign <- function(name){ res <- data.frame(name=c(0,1), Probability=c(0,1)) names(res)[1] <- name res } # produces data frame with prior and posterior lower & upper component survival function # for component of type "name" based on nonParBayesSystemInferencePriorSets() inputs # for all components except survival signature; nLower, nUpper, yLower, yUpper must be data frames # where each column corresponds to the component type, so there must be a match oneCompPriorPostSet <- function(name, at.times, test.data, nLower, nUpper, yLower, yUpper){ sig <- oneCompSurvSign(name) nodata <- list(name=NULL) names(nodata) <- name nL <- nLower[, match(name, names(nLower))] nU <- nUpper[, match(name, names(nUpper))] yL <- yLower[, match(name, names(yLower))] yU <- yUpper[, match(name, names(yUpper))] data <- test.data[match(name, names(test.data))] prio <- nonParBayesSystemInferencePriorSets(at.times, sig, nodata, nL, nU, yL, yU) post <- nonParBayesSystemInferencePriorSets(at.times, sig, data, nL, nU, yL, yU) data.frame(Time=rep(at.times,2), Lower=c(prio$lower,post$lower), Upper=c(prio$upper,post$upper), Item=rep(c("Prior", "Posterior"), each=length(at.times))) } # setting lower and upper y^(0) values from 0 to 0 + eps and 1 to 1 - eps # to avoid errors from nonParBayesSystemInferencePriorSets() not01 <- function(arg, eps=1e-5){ arg[arg == 0] <- eps arg[arg == 1] <- 1 - eps arg } #
21f712af8e9d55bb19cc8855966ec0af89c6b091
[ "R" ]
3
R
geeeero/npb-cens
7d6a968ce4b6f591d545bbf271877653951c50ba
d8077ca261c067ea7b7c43ec5b27300c2df557d8
refs/heads/main
<file_sep>import React, { useEffect, useState } from 'react' import { Container, Icon, Table } from 'semantic-ui-react' import Transaction from '../Transactions/Transactions' const TransactionsList = () => { const [transactions, setTransactions] = useState([]) useEffect(() => { fetch('https://mern-inventory-api.herokuapp.com/api/v1/transactions') .then(res => res.json()) .then(data => { setTransactions(data) }) }, []) return ( <Container> <h3 style={{ textAlign: 'center'}}><Icon name='tag' />Transactions</h3> <Table color='brown'> <Table.Header> <Table.Row> <Table.HeaderCell>Items</Table.HeaderCell> <Table.HeaderCell>Recipient</Table.HeaderCell> <Table.HeaderCell>Agent</Table.HeaderCell> <Table.HeaderCell>Quantity</Table.HeaderCell> <Table.HeaderCell>Date</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> { transactions.map((transaction, i) => { return ( <Transaction key = { i } agent={ transaction.agent} recipient = { transaction.recipient } quantity = { transaction.quantity } consumable = { transaction.consumable } date = { transaction.createdAt } /> ) })} </Table.Body> </Table> </Container> ) } export default TransactionsList<file_sep>import Asset from '../models/asset.model.js' const findAll = (req, res) => { Asset.find({}) .then( data => { if (!data) res.send([]) res.json(data) } ) .catch(err => console.error(err)) } const getById = (req, res) => { const id = req.params.id Asset.findById(id) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const create = (req, res) => { if (!req.body) { console.error({ message: `can't be null` }); res.status(500).send({ message: `can't be null` }) } const asset = new Asset({ name: req.body.name, description: req.body.description, assetNumber: req.body.assetNumber, price: req.body.price, custodian: "Ready for assigning", vendor: req.body.vendor, direction: "in" }) Asset.create(asset) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const update = (req, res) => { const id = req.params.id Asset.findByIdAndUpdate(id, req.body, { new: true }) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({ message: `Can't update asset of id: ${id}` }) console.error(err); }) } const remove = (req, res) => { const id = req.params.id Asset.findByIdAndDelete(id) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({ message: `Can't delete asset of id: ${id}` }) console.error(err); }) } export { findAll, getById, create, update, remove }<file_sep>import express from 'express' import { findAll } from '../middleWares/ldap.js' const ldapRoute = express.Router() ldapRoute .get('/', findAll) export default ldapRoute<file_sep>import express from 'express' import passport from 'passport' import { findAll, getById, update, remove, signUp, logIn } from '../controllers/agent.controller.js' import passportConfig from '../middleWares/passport.js' passportConfig(passport) const agentRoutes = express.Router() agentRoutes .get('', findAll) .get('/:id', getById) .put('/:id', update) .delete('/:id', remove) .post('/signup', signUp) .post('/login', logIn) export default agentRoutes<file_sep>import bcrypt from 'bcrypt' import jsonwebtoken from 'jsonwebtoken' import fs from 'fs' import path, { dirname } from 'path'; import { fileURLToPath } from 'url' const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const privateKeyPath = path.join(__dirname, '..', 'id_rsa_2048_private.pem') const PRIVATE_PUB = fs.readFileSync(privateKeyPath) const saltRounds = 10; const hashPassword = (pwd) => { const salt = bcrypt.genSaltSync(saltRounds); const hash = bcrypt.hashSync(pwd, salt) return { salt: salt, hash: hash } } const comparePassword = (pwd, hash) => { return bcrypt.compare(pwd, hash).then((err, result) => { if(err) console.error(err); return result }); } const issueJWT = (agent) => { const _id = agent._id const agentRole = agent.role const expiresIn = '1d' const payload = { sub: _id, role: agentRole, issueAt: Date.now() } const signedToken = jsonwebtoken.sign(payload, PRIVATE_PUB, { expiresIn: expiresIn, algorithm: 'RS256'}) return { token: "Bearer "+ signedToken, expires: expiresIn } } export { hashPassword, comparePassword, issueJWT }<file_sep>import React, { useState, useEffect } from 'react' import { Table, Button, Icon, Container } from 'semantic-ui-react' import Asset from '../AssetItem/Asset' import { Link } from 'react-router-dom' import jsonwebtoken from 'jsonwebtoken' const AssetList = () => { const [assetList, setAssetList] = useState([]) useEffect(() => { fetch('https://mern-inventory-api.herokuapp.com/api/v1/assets', { headers: {"Access-Control-Allow-Origin": "*"} }) .then(res => { return res.json() }).then(data => { setAssetList(data) }) }, []) const [isAdmin, setIsAdmin] = useState(false) useEffect(() => { if(localStorage.getItem('token') === null) return const token = localStorage.getItem('token').split(" ")[1] const agentRole = jsonwebtoken.decode(token).role if(agentRole === 'admin') { setIsAdmin(true) } }, []) const deleteAsset = (id) => { setAssetList(assetList.filter(asset => asset._id !== id)) fetch('https://mern-inventory-api.herokuapp.com/api/v1/assets/' + id, { method: 'DELETE', headers: {"Access-Control-Allow-Origin": "*"} }) .then((data) => { console.log(`Delete the asset with id ${id}`); }) .catch(err => console.error(err)) } return ( <Container> <h3 style={{ textAlign: 'center'}}><Icon name='tag' />Asset List</h3> { isAdmin ? <Button basic color='teal' animated> <Link to="/assets/create" style={{ color: '#00b5ad'}}><Button.Content visible>Create</Button.Content> <Button.Content hidden> <Icon name='arrow right' /> </Button.Content> </Link> </Button> : <></> } <Table color="brown" selectable> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Description</Table.HeaderCell> <Table.HeaderCell>Asset Number</Table.HeaderCell> <Table.HeaderCell>Price</Table.HeaderCell> <Table.HeaderCell>Custodian</Table.HeaderCell> <Table.HeaderCell>Vendor</Table.HeaderCell> <Table.HeaderCell>In/Out?</Table.HeaderCell> <Table.HeaderCell></Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {assetList.map((asset, i) => { return <Asset key={i} id={asset._id} name={asset.name} description={asset.description} assetNumber={asset.assetNumber} price={asset.price} vendor={asset.vendor} direction={asset.direction} custodian={asset.custodian} deleteAsset={deleteAsset} /> })} </Table.Body> </Table> </Container> ) } export default AssetList<file_sep># mern-inventory ## Frontend Front end using Create React App ## Backend Build the inventory system API / server using Express.js <ol> <li>[x] Assets</li> <li>[x] Consumable</li> <li>[] Software</li> <li>[x] Transaction Logs for consumable</li> <ul> <li>[] may need transaction logs for asset </ul> <li>[x] Users (admin)</li> <li>[x] Custodian (used the test LDAP free server - cited)</li> </ol> Added LDAP from free test server as the custodian of the item and asset (https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/) ## DB: MongoDB <file_sep>import React, { useEffect, useState } from 'react' import { Card, Container, Grid } from 'semantic-ui-react' import HomeItem from '../../components/HomeItem/HomeItem' const Home = () => { const [isLogin, setIsLogin] = useState(localStorage.getItem('token')) useEffect(() => { setIsLogin(localStorage.getItem('token')) }, [isLogin]) const items = [ { name: "Assets", path: '/assets' }, { name: "Consumables", path: '/items'} ] return ( <Container> <div> <h3 style={{textAlign: "center", marginTop: "10%", marginBottom: "5%"}}>Inventory Management</h3> </div> <Card.Group centered> <Grid> <Grid.Row columns={2}></Grid.Row> <Grid.Row columns={2}> { items.map((item, key) => { return ( <Grid.Column stretched> <HomeItem key={ key } itemName = { item.name } path= { item.path } isAuth = {isLogin} /> </Grid.Column> ) }) } </Grid.Row> </Grid> </Card.Group> </Container> ) } export default Home<file_sep>import React from 'react' import AssetForm from '../AssetForm/AssetForm' import { useParams} from "react-router-dom"; import { Container, Header, Icon } from 'semantic-ui-react'; const AddEditAsset = () => { const { id } = useParams() return ( <Container> <Header as='h3' icon textAlign='center' color='violet'> <Icon name='upload' circular /> <Header.Content>Create Asset</Header.Content> </Header> <AssetForm assetId={id}/> </Container> ) } export default AddEditAsset;<file_sep>import mongoose from 'mongoose' const Schema = mongoose.Schema const consumableSchema = new Schema({ name: { type: String, required: true }, description: { type: String, required: true }, quantity: { type: Number, required: true }, price: { type: Number, required: true }, vendor: { type: String, required: true } }, { timestamps: true}) const Consumable = mongoose.model('Consumable', consumableSchema) export default Consumable;<file_sep>import './App.css'; import NavBar from './components/NavBar/NavBar' import AssetList from './components/AssetList/AssetList' import Home from './pages/home-page/home-page'; import { Route, Switch, } from "react-router-dom"; import AddEditAsset from './components/AddEditAsset/AddEditAsset'; import ConsumableList from './components/ConsumableList/ConsumableList'; import AddEditConsumable from './components/AddEditConsumable/AddEditConsumable'; import React , { useEffect, useState } from 'react'; import ProtectedRoute from './components/ProtectedRoute/ProtectedRoute'; import { Container } from 'semantic-ui-react'; import TransactionForm from './components/TransactionForm/TransactionForm'; import TransactionsList from './components/TransactionsList/TransactionsList'; import CheckOutAsset from './components/CheckOutAsset/CheckOutAsset'; import LoginPage from './pages/login-page/login-page'; import AdminRoute from './components/AdminRoute/AdminRoute'; import jsonwebtoken from 'jsonwebtoken' import ErrorPage from './pages/error-page/error-page'; function App() { const [isLogin, setIsLogin] = useState(localStorage.getItem('token')) const [isAdmin, setIsAdmin] = useState(false) useEffect(() => { setIsLogin(localStorage.getItem('token')) }, [isLogin]) useEffect(() => { if(localStorage.getItem('token') === null) return const token = localStorage.getItem('token').split(" ")[1] const agentRole = jsonwebtoken.decode(token).role if(agentRole === 'admin') { setIsAdmin(true) } }, []) if(isLogin !== null) { return ( <Container> <NavBar isAuth={isLogin}/> <br /> <Switch> <Route path="/" exact component={Home}/> <ProtectedRoute path="/assets" exact component={AssetList} isAuth={isLogin}/> <AdminRoute path="/assets/create" exact component={AddEditAsset} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> <AdminRoute path="/assets/:id/edit" exact component={AddEditAsset} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> <AdminRoute path="/assets/:id/checkout" exact component={CheckOutAsset} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> <ProtectedRoute path="/items" exact component={ConsumableList} isAuth={isLogin}/> <AdminRoute path="/items/create" exact component={AddEditConsumable} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> <AdminRoute path="/items/:id/edit" exact component={AddEditConsumable} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> <ProtectedRoute path="/transactions/" exact component={TransactionsList} isAuth={isLogin} /> <AdminRoute path="/transactions/:id/checkout" exact component={TransactionForm} errorComponent={ErrorPage} isAuth={isLogin} isAdmin={isAdmin}/> </Switch> </Container> ); } else { return ( <Container> <NavBar isAuth={isLogin}/> <Route path="/" exact component={Home}/> <Route path="/login" exact component={LoginPage}/> {/* <NavBar isAuth={isLogin}/> */} {/* <LoginPage /> */} </Container> ) } } export default App; <file_sep>import React from 'react' import { Icon, Message } from 'semantic-ui-react' const ErrorPage = () => ( <Message negative icon> <Icon name='circle notched' loading /> <Message.Content> <Message.Header>We're sorry, you don't have admin permission</Message.Header> <p>Redirecting back to Home page in 3 seconds</p> </Message.Content> </Message> ) export default ErrorPage<file_sep>import express from 'express' import { findAll, getById, create, update, remove } from '../controllers/transaction.controller.js' const transactionRoutes = express.Router() transactionRoutes .get('/', findAll) .get('/:id', getById) .post('/:id', create) .put('/:id', update) .delete('/:id', remove) export default transactionRoutes<file_sep>import mongoose from 'mongoose' const Schema = mongoose.Schema const agentSchema = new Schema({ username: { type: String, required: true }, firstname: { type: String, required: true }, lastname: { type: String, required: true }, salt: { type: String, required: true }, hash: { type: String, required: true }, email: { type: String, required: true }, role: { type: String, required: true } }, { timestamps: true}) const Agent = mongoose.model('Agent', agentSchema) export default Agent;<file_sep>import React from 'react' import { useParams } from 'react-router-dom' import { Container, Header, Icon } from 'semantic-ui-react' import ConsumableForm from '../ComsumableForm/ConsumableForm' const AddEditConsumable = () => { const id = useParams() return ( <Container> <Header as='h3' icon textAlign='center' color='violet'> <Icon name='upload' circular /> <Header.Content>Create Item</Header.Content> </Header> <ConsumableForm id={ id }/> </Container> ) } export default AddEditConsumable<file_sep>import Consumable from '../models/consumable.model.js' const findAll = (req, res) => { Consumable.find({}) .then( data => { if(!data) res.send([]) res.send(data) } ) .catch(err => console.error(err)) } const getById = (req, res) => { const id = req.params.id Consumable.findById(id) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const create = (req, res) => { if(!req.body.name) { console.error({message: `can't be null`}); res.status(500).send({message: `can't be null`}) } const consumable = new Consumable({ name: req.body.name, description: req.body.description, quantity: req.body.quantity, price: req.body.price, vendor: req.body.vendor, }) Consumable.create(consumable) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const update = (req, res) => { const id = req.params.id Consumable.findByIdAndUpdate(id, req.body, { new: true }) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({message: `Can't update item of id: ${id}`}) console.error(err); }) } const remove = (req, res) => { const id = req.params.id Consumable.findByIdAndDelete(id) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({message: `Can't delete item of id: ${id}`}) console.error(err); }) } export { findAll, getById, create, update, remove }<file_sep>import React from 'react' import { Table } from 'semantic-ui-react' const Transaction = ({ agent, recipient, consumable, quantity, date }) => { return ( <> <Table.Row> <Table.Cell>{ consumable }</Table.Cell> <Table.Cell>{ recipient }</Table.Cell> <Table.Cell>{ agent }</Table.Cell> <Table.Cell>{ quantity }</Table.Cell> <Table.Cell>{ date }</Table.Cell> </Table.Row> </> ) } export default Transaction<file_sep>import React, { Component } from 'react' import { Menu } from 'semantic-ui-react' import { NavLink } from 'react-router-dom' class NavBar extends Component { constructor(props) { super(props) this.state = { activeItem: 'home', } } handleItemClick = ({ name }) => this.setState({ activeItem: name }) handleLogOut = (e) => { e.preventDefault() localStorage.removeItem('token') localStorage.removeItem('expires'); window.location.replace('/') } render() { const { activeItem } = this.state if(this.props.isAuth === null || "") { return ( <Menu pointing secondary> <NavLink to="/login"> <Menu.Item name='Login' active={activeItem === 'Login'} onClick={this.handleItemClick} /> </NavLink> </Menu> ) } else { return ( <Menu pointing secondary> <NavLink to="/"> <Menu.Item name='home' active={activeItem === 'home'} onClick={this.handleItemClick} /> </NavLink> <NavLink to="/assets"> <Menu.Item name='asset' active={activeItem === 'asset'} onClick={this.handleItemClick} /> </NavLink> <NavLink to="/items"> <Menu.Item name='consumable' active={activeItem === 'consumable'} onClick={this.handleItemClick} /> </NavLink> <NavLink to="/transactions"> <Menu.Item name='transactions' active={activeItem === 'transactions'} onClick={this.handleItemClick} /> </NavLink> <Menu.Menu position='right'> <NavLink to="/"> <Menu.Item name='logout' active={activeItem === 'logout'} onClick={this.handleLogOut} /> </NavLink> </Menu.Menu> </Menu> ) } } } export default NavBar;<file_sep>import React from 'react' import LoginForm from '../../components/LoginForm/LoginForm' const LoginPage = (props) => { return ( <LoginForm props={props}/> ) } export default LoginPage<file_sep>import mongoose from 'mongoose' const Schema = mongoose.Schema const assetSchema = new Schema({ name: { type: String, required: true }, description: { type: String, required: true }, assetNumber: { type: Number, required: true }, price: { type: Number, required: true }, custodian: { type: String, required: true }, vendor: { type: String, required: true }, direction: { type: String, enum: ['in', 'out'], required: true } }, { timestamps: true}) const Asset = mongoose.model('Asset', assetSchema) export default Asset;<file_sep>import Transaction from '../models/transaction.model.js' const findAll = (req, res) => { Transaction.find({}) .then( data => { if(!data) res.send([]) res.send(data) } ) .catch(err => console.error(err)) } const getById = (req, res) => { const id = req.params.id Transaction.findById(id) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const create = (req, res) => { if(!req.body) { console.error({message: `can't be null`}); res.status(500).send({message: `can't be null`}) } const transaction = new Transaction({ agent: req.body.agent, recipient: req.body.recipient, quantity: req.body.quantity, note: req.body.note, consumable: req.body.consumable }) Transaction.create(transaction) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const update = (req, res) => { const id = req.params.id Transaction.findByIdAndUpdate(id, req.body, { new: true }) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({message: `Can't update transaction of id: ${id}`}) console.error(err); }) } const remove = (req, res) => { const id = req.params.id Transaction.findByIdAndDelete(id) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({message: `Can't delete transaction of id: ${id}`}) console.error(err); }) } export { findAll, getById, create, update, remove }<file_sep>import Agent from "../models/agent.model.js" import { hashPassword, comparePassword, issueJWT } from '../helpers/passwordUtils.js' const signUp = (req, res) => { if (!req.body) { console.error({ message: `can't be null` }); res.status(500).send({ message: `can't be null` }) } const saltHash = hashPassword(req.body.password) const salt = saltHash.salt const hash = saltHash.hash const agent = new Agent({ username: req.body.username, firstname: req.body.firstname, lastname: req.body.lastname, salt: salt, hash: hash, email: req.body.email, role: req.body.role }) Agent.create(agent) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const logIn = (req, res, next) => { Agent.findOne({ username: req.body.username }) .then((agent) => { if(!agent) { return res.status(401).json({ success: false, msg: "could not find user" }) } const isValid = comparePassword(req.body.password, agent.hash) if(isValid) { const tokenObj = issueJWT(agent) res.status(200).json({ success: true, agent: agent, token: tokenObj.token, expiresIn: tokenObj.expires }) } else { res.status(401).json({ success: false, msg: "you entered the wrong password" }); } }) .catch((err) => { next(err); }); } const findAll = (req, res) => { Agent.find({}) .then( data => { if (!data) res.send([]) res.json(data) } ) .catch(err => console.error(err)) } const getById = (req, res) => { const id = req.params.id Agent.findById(id) .then(data => { res.send(data) }) .catch(err => { console.error(err); }) } const update = (req, res) => { const id = req.params.id Agent.findByIdAndUpdate(id, req.body, { new: true }) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({ message: `Can't update Agent of id: ${id}` }) console.error(err); }) } const remove = (req, res) => { const id = req.params.id Agent.findByIdAndDelete(id) .then(response => { res.send(response) }) .catch(err => { res.status(500).send({ message: `Can't delete Agent of id: ${id}` }) console.error(err); }) } export { findAll, getById, update, remove, signUp, logIn }<file_sep>import mongoose from 'mongoose' import dotenv from 'dotenv' dotenv.config() const mongoUri = process.env.MONGO_URI mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true }) mongoose.Promise = global.Promise const db = mongoose.connection export default db<file_sep>import React, { useEffect, useState } from 'react' import { Link, Redirect } from 'react-router-dom' import { Button, Form } from 'semantic-ui-react' const ConsumableForm = (props) => { const [consumable, setConsumable] = useState({ name: props.consumable ? this.props.name : '', description: props.consumable ? this.props.description : '', quantity: props.consumable ? this.props.quantity : 0, price: props.consumable ? this.props.price : 0, vendor: props.consumable ? this.props.vendor : '', }) const [isEditing, setIsEditing] = useState(false) const [toHome, setToHome] = useState(false) const { name, description, quantity, price, vendor} = consumable const {id} = props.id useEffect(() => { fetch('https://mern-inventory-api.herokuapp.com/api/v1/items/' + id) .then(res => { return res.json() }) .then(data => { setConsumable(data) setIsEditing(true) }) .catch(err => { console.err(err) }) }, [id]) const onChangeHandler = (e) => { e.preventDefault() const { name, value } = e.target setConsumable({ ...consumable, [name] : value }) } const handleSubmit = (e) => { e.preventDefault() const data = { name, description, quantity, price, vendor } if(isEditing) { fetch('https://mern-inventory-api.herokuapp.com/api/v1/items/' + id, { method: 'PUT', headers: { 'Content-type': 'application/json', "Access-Control-Allow-Origin": "*" }, body: JSON.stringify(data) }) .then() .catch(err => console.error(err)) } else { fetch('https://mern-inventory-api.herokuapp.com/api/v1/items', { method: 'POST', headers: { 'Content-type': 'application/json', "Access-Control-Allow-Origin": "*" }, body: JSON.stringify(data) }) .then() .catch(err => console.error(err)) } setToHome(true) } if(toHome) { return <Redirect to="/items" /> } return ( <Form> <Form.Field> <label>Name</label> <input name='name' type='text' value={name} onChange={onChangeHandler} placeholder='Asset name' /> </Form.Field> <Form.Field> <label>Description</label> <input name='description' value={description} onChange={onChangeHandler} placeholder='Description' /> </Form.Field> <Form.Field> <label>Quantity</label> <input type='number' value={quantity} onChange={onChangeHandler} name='quantity' placeholder='Quantity' /> </Form.Field> <Form.Field> <label>Price</label> <input type='number' value={price} onChange={onChangeHandler} name='price' placeholder='Price' /> </Form.Field> <Form.Field> <label>Vendor</label> <input name='vendor' value={vendor} onChange={onChangeHandler} placeholder='Vendor' /> </Form.Field> <Button.Group> <Link to='/items/'><Button color='red'>Cancel</Button></Link> <Button.Or /> <Button positive onClick={handleSubmit} type='submit'>Submit</Button> </Button.Group> </Form> ) } export default ConsumableForm<file_sep>import ldap from 'ldapjs' const opts = { url: 'ldap://ldap.forumsys.com', port: '389' } const ldapClient = ldap.createClient(opts) ldapClient.bind('cn=read-only-admin,dc=example,dc=com', 'password', (err, res) => { if (err) { console.log(err); client.unbind(); return; } }) const findAll = (req, res, next) => { let entries = [] const searchOpts = { filter: '(objectClass=*)', scope: 'sub', attributes: ['dn', 'cn', 'displayName', 'mail', 'sAMAccountName'] } ldapClient.search('dc=example,dc=com', searchOpts, function (err, result) { result.on('searchEntry', (entry) => { // console.log('entry: ' + JSON.stringify(entry.object)); entries.push(entry.object) }); result.on('error', function(err) { ldapClient.unbind(); return err }); result.on('end', function(response) { if(response.status != 0) res.status(404).send("User not found"); res.json(entries) next() }); }) } export { findAll } <file_sep>import React, { useEffect, useState } from 'react' import { Link, useParams } from 'react-router-dom' import { Button, Container, Header, Icon, Label, Select } from 'semantic-ui-react' const CheckOutAsset = () => { const assetId = useParams().id const [custodians, setCustodians] = useState([]) const [selectedCustodian, setSelectedCustodian] = useState('No selected custodian') const [selectedAsset, setSelectedAsset] = useState([]) const selectedCustodianHandler = (e) => { e.preventDefault() setSelectedCustodian(e.target.textContent) } const submitHandler = (e) => { e.preventDefault() const updatedAsset = { ...selectedAsset, custodian: selectedCustodian, direction: 'out' } fetch(`https://mern-inventory-api.herokuapp.com/api/v1/assets/${assetId}`, { method: 'PUT', headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedAsset) }) .then(res => console.log(res)) .catch(err => console.error(err)) } useEffect(() => { fetch('https://mern-inventory-api.herokuapp.com/ldap') .then(res => res.json()) .then(data => data.map((user, i) => { return { text: user.cn, value: user.cn , key: i} }) ) .then(result => setCustodians(result)) }, []) useEffect(() => { fetch(`https://mern-inventory-api.herokuapp.com/api/v1/assets/${assetId}`) .then(res => res.json()) .then(data => { setSelectedAsset(data) }) }) return ( <Container> <Header as='h3' icon textAlign='center' color='teal'> <Icon name='upload' circular /> <Header.Content>Check Out Asset</Header.Content> </Header> <br /> <Container textAlign='center'> Custodian: <Select search searchInput={{ type: 'string' }} selection options={custodians} placeholder='Select users' onChange={selectedCustodianHandler} /> </Container> <br /> <br /> <Container fluid> <Button.Group> <Link to='/assets/'><Button color='red'>Cancel</Button></Link> <Button.Or /> <Button icon color='green' onClick={submitHandler}> <Icon name='check circle outline'/> Check Out </Button> <Label as='a' basic pointing='left'> { selectedCustodian } is being assigned to { selectedAsset.name } with Asset Number: { selectedAsset.assetNumber } </Label> </Button.Group> </Container> </Container> ) } export default CheckOutAsset<file_sep>import express from 'express' import cors from 'cors' import dotenv from 'dotenv' import db from './helpers/db.js' import assetRoutes from './routes/asset.route.js' import consumableRoutes from './routes/consumable.route.js' import agentRoutes from './routes/agent.route.js' import passport from 'passport' import transactionRoutes from './routes/transaction.route.js' import ldapRoute from './routes/ldap.route.js' dotenv.config() const app = express() const port = process.env.PORT db.on('error', (err) => { console.error(err); }) db.on('connected', () => { console.log('Mongodb is connected'); }).then(() => { app.use(cors()) app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.use(passport.initialize()) app.use('/api/v1/assets', assetRoutes) app.use('/api/v1/items', consumableRoutes) app.use('/api/v1/agents', agentRoutes) app.use('/api/v1/transactions', transactionRoutes) app.use('/ldap', ldapRoute) app.listen(port || 3001, () => { console.log(`API is running on ${port}`); }) }) <file_sep>import express from 'express' import { findAll, getById, create, update, remove } from '../controllers/consumable.controller.js' const consumableRoutes = express.Router() consumableRoutes .get('/', findAll) .get('/:id', getById) .post('/', create) .put('/:id', update) .delete('/:id', remove) export default consumableRoutes<file_sep>import React, { useEffect, useState } from 'react' import { Link } from 'react-router-dom' import './Asset.css' import jsonwebtoken from 'jsonwebtoken' import { Table, Button, Icon, Grid } from 'semantic-ui-react' const Asset = ({ id, name, description, assetNumber, price, custodian, vendor, direction, deleteAsset }) => { const [isAdmin, setIsAdmin] = useState(false) useEffect(() => { if(localStorage.getItem('token') === null) return const token = localStorage.getItem('token').split(" ")[1] const agentRole = jsonwebtoken.decode(token).role if(agentRole === 'admin') { setIsAdmin(true) } }, []) if (direction === 'out') { return ( <Table.Row disabled> <Table.Cell>{name}</Table.Cell> <Table.Cell>{description}</Table.Cell> <Table.Cell>{assetNumber}</Table.Cell> <Table.Cell>{price}</Table.Cell> <Table.Cell>{custodian}</Table.Cell> <Table.Cell>{vendor}</Table.Cell> <Table.Cell>{direction}</Table.Cell> </Table.Row> ) } else { return ( <Table.Row> <Table.Cell>{name}</Table.Cell> <Table.Cell>{description}</Table.Cell> <Table.Cell>{assetNumber}</Table.Cell> <Table.Cell>{price}</Table.Cell> <Table.Cell>{custodian}</Table.Cell> <Table.Cell>{vendor}</Table.Cell> <Table.Cell>{direction}</Table.Cell> { isAdmin ? <Table.Cell> <Grid columns={3} divided> <Grid.Row> <Grid.Column> <Button basic color='violet' animated> <Link style={{ textDecorationColor: 'none', textDecoration: 'none' ,color: '#6435c9'}} to={`/assets/${id}/edit`} > <Button.Content visible>Edit</Button.Content> <Button.Content hidden> <Icon name='edit outline' /> </Button.Content> </Link> </Button> </Grid.Column> <Grid.Column> <Button basic color='yellow' animated> <Link style={{ textDecorationColor: 'none', textDecoration: 'none' ,color: '#fbbd08'}} to={`/assets/${id}/checkout`} > <Button.Content visible>Check out!</Button.Content> <Button.Content hidden> <Icon name='opencart' /> </Button.Content> </Link> </Button> </Grid.Column> <Grid.Column> <Button basic color='red' onClick={() => deleteAsset(id)} animated> <Button.Content visible>Delete</Button.Content> <Button.Content hidden> <Icon name='trash alternate outline' /> </Button.Content> </Button> </Grid.Column> </Grid.Row> </Grid> </Table.Cell> : <></> } </Table.Row> ) } } export default Asset
97445d471082a8f04c0905e830c6b047c346951a
[ "JavaScript", "Markdown" ]
29
JavaScript
kentiet/mern-inventory
13050e0923df2b1955b6736e8a91f48962003cca
f8deedec5f368ca297fd700e101a750a3e79b025
refs/heads/master
<repo_name>segfault88/misc-go<file_sep>/wg-gotcha-fixed.go package main import ( "log" "math/rand" "sync" "time" ) func main() { var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go doWork(i, &wg) } log.Println("Starting to wait") wg.Wait() log.Println("Done") } func doWork(i int, wg *sync.WaitGroup) { defer wg.Done() sleepTime := time.Duration(rand.Int31n(10000000)) time.Sleep(sleepTime) log.Printf("%d slept for %d", i, sleepTime) }
5c7bf798db705619bff4f688e3572cc56bc58784
[ "Go" ]
1
Go
segfault88/misc-go
3376704825d69f5a1045f8dd2aee2addd5cb7394
92fbb3c4af17a71f3f6c8171d8902b73f690066c
refs/heads/master
<repo_name>Anthnoybs/PHP-simple_algorithm_collection<file_sep>/algo3.php <?php for ($i=0; $i <13 ; $i++) { $results = $i*13; echo $i .'X 13 = '. $results. '<br>' ; } ?><file_sep>/algo2.php <?php for ($i=0; $i <500 ; $i++) { echo "je fais des sauvegarde regulières de mes fichiers !<br> "; } ?><file_sep>/tableauaffiche.php <?php $tableau = array(); function tab($content){ global $tableau; array_unshift($tableau, $content); } tab("cbhjrbcr"); function affiche(){ global $tableau; echo "<pre>"; print_r($tableau); echo "</pre>"; } tab("nehrvneuvhne"); affiche(); ?> <file_sep>/calendrier.php <?php $date = getdate(); function calendrier( int $mois, int $annee){ global $date; $nombreJours = cal_days_in_month(CAL_GREGORIAN, $mois, $annee); $prems = date("N", mktime(0, 0, 0, $mois, 1, $annee)); if ($prems == 0 ) { $prems == 7 ; } echo "<table>"; echo "<tr><th>Lun</th><th>Mar</th><th>Mer</th><th>Jeu</th><th>Ven</th><th>Sam</th><th>Dim</th></tr>"; echo "<tr>"; $compteur = 1 ; echo "<h2>". $mois ." /" .$annee . "</h2>"; echo "<tr>"; for ($i=1; $i <= 7 ; $i++) { echo "<td>"; if ($i< $prems) { echo " "; } else{ echo $compteur; $compteur++; } echo "</td>"; } echo "</tr><tr>"; for ($j=1; $j<= 7 ; $j++) { echo "<td>" . $compteur ."</td>"; $compteur++; } echo "</tr><tr>"; for ($k=1; $k<= 7 ; $k++) { echo "<td>" . $compteur ."</td>"; $compteur++; } echo "</tr><tr>"; for ($l=1; $l<= 7 ; $l++) { echo "<td>" . $compteur ."</td>"; $compteur++; } echo "</tr><tr>"; for ($m=1; $m<= 7 ; $m++) { if ($compteur <= $nombreJours) { echo "<td>" . $compteur ."</td>"; $compteur++; } else{ echo "<td> </td>"; } } echo "</table>"; } calendrier(7,$date["year"]); <file_sep>/algo7.php <?php function triangle($lignes){ for ($i=0; $i < $lignes ; $i++) { echo "<br>"; for ($j=0; $j < $i ; $j++) { echo "*"; } } } triangle(4); triangle(8); triangle(16);<file_sep>/algo4.php <?php $nombre = 1; for ($i=1 ; $i<=30 ; $i++) { $nombre = $nombre * $i; } echo $nombre;<file_sep>/batailleNav.php <?php function bataille($lettre,$chiffre){ $posLettre = ord(strtolower($lettre))-96; if ($posLettre<0 || $posLettre>10 || $chiffre<0 || $chiffre>10) { echo "hors jeux!"; exit ; } else{ $tab = [ 1 => array(1,2,3,4,5,6,7,8,9,10), 2 => array(1,2,3,4,5,6,7,8,9,10), 3 => array(1,2,3,4,5,6,'',8,9,10), 4 => array(1,2,3,4,5,6,'',8,9,10), 5 => array(1,2,3,4,5,6,'',8,'',10), 6 => array(1,2,3,4,5,6,7,8,'',10), 7 => array(1,2,3,4,5,6,7,8,9,10), 8 => array(1,2,3,4,5,6,7,8,9,10), 9 => array(1,2,'','','','',7,8,9,10), 10=> array(1,2,3,4,5,6,7,8,9,10), ]; $row = $tab[$chiffre]; $col = $row[$posLettre]; if ( is_string($col)) { echo "Touché ! ";} else{echo "manqué!";} } } bataille('c',9); ?> <file_sep>/algoMesureString.php <?php function mesure($chaine){ $nike = strlen($chaine); echo $nike; } mesure('eeeeevzzvzverrerververevervreververvez'); ?><file_sep>/majuscule.php <?php function maju($variable){ $gogol = ucwords($variable); echo $gogol; } maju("je suis un gros gogol "); ?>
6c5fa4b94e6f58d2b1ca24fea0765508de7b1f4a
[ "PHP" ]
9
PHP
Anthnoybs/PHP-simple_algorithm_collection
e27986c4afd818621d7f81f883388d4d0ec795f0
7584db8586b950595e2f59ce6b20471b22a241f6
refs/heads/master
<file_sep>/** * * * * * * */ package Dhvani; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.dynamodb.AmazonDynamoDBClient; import com.amazonaws.services.dynamodb.model.AttributeValue; import com.amazonaws.services.dynamodb.model.ComparisonOperator; import com.amazonaws.services.dynamodb.model.Condition; import com.amazonaws.services.dynamodb.model.CreateTableRequest; import com.amazonaws.services.dynamodb.model.DescribeTableRequest; import com.amazonaws.services.dynamodb.model.KeySchema; import com.amazonaws.services.dynamodb.model.KeySchemaElement; import com.amazonaws.services.dynamodb.model.ProvisionedThroughput; import com.amazonaws.services.dynamodb.model.PutItemRequest; import com.amazonaws.services.dynamodb.model.PutItemResult; import com.amazonaws.services.dynamodb.model.ScanRequest; import com.amazonaws.services.dynamodb.model.ScanResult; import com.amazonaws.services.dynamodb.model.TableDescription; import com.amazonaws.services.dynamodb.model.TableStatus; // Import JSON related libraries import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Ingest { /* * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials. * http://aws.amazon.com/security-credentials */ static AmazonDynamoDBClient dynamoDB; /** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { AWSCredentials credentials = new PropertiesCredentials( AmazonDynamoDBSample.class.getResourceAsStream("AwsCredentials.properties")); dynamoDB = new AmazonDynamoDBClient(credentials); } public static void ingestFP(String[] args) throws Exception { init(); // This method takes the file name as parameter. The file is in JSON format //decalring the variables for storing the fields extracted from the JSON formatted files. String code; String track_id; int length; String version; String artist; String title; String release; JSONArray songList = (JSONArray) parser.parse(new FileReader(args[0])); for (Object songObject : songList) { JSONObject song = (JSONObject) songObject; code = (String) song.get("code"); System.out.println(code); JSONArray metadata = (JSONArray) jsonObject.get("metadata"); for (Object metaObject: metadata) { track_id = metaObject.get("track_id"); length = metaObject.get("duration"); version = metaObject.get("version"); artist = "none"; artist = metaObject.get("artist"); title = "none"; title = metaObject.get("title"); release = "none"; release = metaObject.get("release"); } // For each song, call the insert method putItemIntoTable(code, track_id, length, version, artist, title, release); } try { String tableName = "DhvaniSongsTable"; // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); // Scan database for presence of these fingerprints HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1985")); scanFilter.put("year", condition); ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter); ScanResult scanResult = dynamoDB.scan(scanRequest); System.out.println("Result: " + scanResult); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } private static Map<String, AttributeValue> newItem(String track_id,int length,String version,String artist,String title,String release) { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put("track_id", new AttributeValue(track_id)); item.put("length", new AttributeValue().withN(Integer.toString(length))); item.put("version", new AttributeValue(version)); item.put("artist", new AttributeValue(artist)); item.put("title", new AttributeValue(title)); item.put("release", new AttributeValue(release)); return item; } private static Map<String, AttributeValue> newCode(String track_id,int hashKeyCode,int timeStamp) { Map<String, AttributeValue> hashCode = new HashMap<String, AttributeValue>(); //insert the track ID hashCode.put("track_id", new AttributeValue(track_id)); //insert the hash key code hashCode.put("hashKeyCode", new AttributeValue().withN(Integer.toString(hashKeyCode)); //insert the timestamp of that hash key code hashCode.put("timeStamp", new AttributeValue().withN(Integer.toString(timeStamp))); } // return the item with Track ID and Hash Key inserted return hashCode; } private static void putItemIntoTable(String code, String track_id,int length,String version,String artist,String title,String release) { // Add an item Map<String, AttributeValue> songRecord = newItem(track_id, length, version, artist, title, release); //Set table name to the Songs table tableName = "DhvaniSongsTable"; PutItemRequest putItemsRequest = new PutItemRequest(tableName, songRecord); PutItemResult putItemsResult = dynamoDB.putItem(putItemsRequest); System.out.println("Result: " + putItemsResult); //Set table name to the hash code table tableName = "DhvaniHashCodeTable"; //check if the fingerprint already exists String checkSong = new SearchFP().searchFPrint(code); //if the fingerprint already exists, the method returns the song details, else it is blank if(checkSong != " ") { StringTokenizer hashKeyToken = new StringTokenizer(code,","); while(hashKeyToken.hasMoreTokens()) { String hashKey = hashKeyToken.nextToken(); StringTokenizer timeToken = new StringTokenizer(hashKey,":"); while(timeToken.hasMoreTokens()) { //extract the hash Key from the string. int hashKeyCode = Integer.parseInt(timeToken.nextToken()); //extract the time stamp from the string. int timeStamp = Integer.parseInt(timeToken.nextToken()); //insert hashcode into DhvaniHashCode Table Map<String, AttributeValue> hashKeyRecord = newCode(track_id, hashKeyCode,timeStamp ); PutItemRequest putHashCodeRequest = new PutItemRequest(tableName, hashKeyRecord); PutItemResult putHashResult = dynamoDB.putItem(putHashCodeRequest); System.out.println("Result: " + putHashResult); } } } } private static void waitForTableToBecomeAvailable(String tableName) { System.out.println("Waiting for " + tableName + " to become ACTIVE..."); long startTime = System.currentTimeMillis(); long endTime = startTime + (10 * 60 * 1000); while (System.currentTimeMillis() < endTime) { try {Thread.sleep(1000 * 20);} catch (Exception e) {} try { DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(request).getTable(); String tableStatus = tableDescription.getTableStatus(); System.out.println(" - current state: " + tableStatus); if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; } catch (AmazonServiceException ase) { if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == false) throw ase; } } throw new RuntimeException("Table " + tableName + " never went active"); } } <file_sep>package Dhvani.Test; import Dhvani.*; import org.junit.*; public class RecommendationTest { @Test public void testingmethod0() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/MJ/You Rock My World.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod1() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/Eminem/Real Slim Shady.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod2() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/Eminem/Superman.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod3() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/<NAME>/love.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod4() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/<NAME>/You belong with me.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod5() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/MJ/They don't care about us.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod6() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/MJ/Beat it.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod7() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/Fray/Backwards.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod8() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/Shakira/Whenever.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod9() { Recommendation mywrapper = new Recommedation(); String filepath = "E:/Songs/Shakira/Hips dont lie.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } @Test public void testingmethod10() { Recommendation mywrapper = new Recommendation(); String filepath = "E:/Songs/NickelBack/Someday.mp3"; try { mywrapper.RecommendSong(filepath); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>package Dhvani; /** * * @author divchag * */ public class InjestionMain { //This is the map reduce main program that will be triggered when we initially //dump hundreds of songs into database. // public static void main(String[] args) throws Exception { //job is to be configured with input location and output location //as arguments to main function where the parameters will be set correspondingly. //So the location of input directory in s3 bucket where songs are present JobConf job = new JobConf(InjestionMain.class); job.setJobName("INJESTIONMAIN"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); //Mapping mapper and reducer classes job.setMapperClass(InjestionMapper.class); job.setReducerClass(InjestionReducer.class); job.setInputFormat(TextInputFormat.class); job.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); //triggering the configured job. JobClient.runJob(job); } } <file_sep>package Dhvani; import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; import java.util.Collections; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Recommendation { private static String driverName = "org.apache.hive.jdbc.HiveDriver"; /** * @param args * @throws SQLException */ public static void findRecommendation(String codeStr) throws SQLException { //Storing the code string passed as parameter String codeString = codeStr; try { Class.forName(driverName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } // setting the connection to hive2 server Connection connection = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "DhvaniUser1", ""); Statement stmt = connection.createStatement(); String dbTableName = "HiveUserTable"; //drop reference table if already exists stmt.execute("drop table if exists " + dbTableName); //create external reference Hive table to refer data from DynamoDB stmt.execute("create external table " + dbTableName + " (HiveUserId int, HivePlaylistArray ArrayList<String>, "+ "HiveTimeArray ArrayList<int>)" ); //+ " Stored by 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'" + "TBLPROPERTIES (" + '"' + "dynamodb.table.name" + '" =' + ""DhvaniUserTable", "dynamodb.column.mapping" " " + +" = "HiveUserId : userId, HivePlaylistArray: PlaylistArray, HiveTimeArray:timeArray" )"; String sql = "show tables '" + dbTableName + "'"; System.out.println("Running : " + sql); ResultSet rset = stmt.executeQuery(sql); if (rset.next()) { System.out.println(rset.getString(1)); } String SelectSQL = "Select HiveUserId, HiveSongId from " + dbTableName + " Where HiveHashKey in " + qrySongId ; ResultSet qryResult1 = stmt.executeQuery(SelectSQL); ResultSet qryResult2 = qryResult1; return qryResult2; // search for hash Keys in the database String SelectSQL = "Select Genre from " + dbTableName + " Where TrackArray is " + Tab2.playlist.TrackArray ; ResultSet qryResult1 = stmt.executeQuery(SelectSQL); ResultSet qryResult2 = qryResult1; // Here, qryresult2 gives us the genre String SelectSQL = "Select TrackArray from "dbTableName + "Where genre is " + qryresult.getData(); ResultSet qryResult3 = stmt.executeQuery(SelectSQL); ArrayList<String> RecommendationList = new ArrayList<String>(); RecommendationList = qryResult3.getArray("HiveTracksArray"); } }
e14145a71cf3a03ed08b69cbc8e275cfd9de1763
[ "Java" ]
4
Java
Dhvani-UFL/Ingesting-Searching
79a976583cfcca7b7597d516758ef7d3a553c77d
27986821afafe546c8afa0740cbfd945364c9339
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BilgiIslemEnvanter.MyClasses { public class TonerZimmet { public int YaziciID { get; set; } public string YaziciMarka { get; set; } public string YaziciModel { get; set; } public string YaziciSeriNo { get; set; } public bool Durum { get; set; } public bool Zimmet { get; set; } public bool BirimID { get; set; } public bool PersonelID { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class TonerController : Controller { // GET: Toner BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Liste() { var listele = db.Yazicilar.Where(x => x.ZIMMET == true).ToList(); return View(listele); } [HttpGet] public ActionResult TonerGiris() { List<SelectListItem> degerler1 = (from i in db.YaziciMarkalari.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.YAZICIMARKA, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr1 = degerler1; List<SelectListItem> degerler2 = (from i in db.YaziciModelleri.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.YAZICIMODEL, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr2 = degerler2; return View(); } [HttpPost] public ActionResult TonerGiris(TonerGiris p) { var markasi = db.YaziciMarkalari.Where(m => m.ID == p.YaziciMarkalari.ID).FirstOrDefault(); p.YaziciMarkalari = markasi; var modeli = db.YaziciModelleri.Where(m => m.ID == p.YaziciModelleri.ID).FirstOrDefault(); p.YaziciModelleri = modeli; if (p.TONERADET == null) { return View("TonerGiris"); } db.TonerGiris.Add(p); p.DURUM = true; //Bilgisayar Id ile buldu ve zimmet alanını true'ye çevirdi. var TonerEkle = db.TonerStok.FirstOrDefault(x => x.YAZICIMARKALARIID == p.YAZICIMARKA && x.YAZICIMODELLERIID == p.YAZICIMODEL); TonerEkle.KALANTONER += p.TONERADET; TonerEkle.KALANDRUM += p.DRUMADET; db.Entry(TonerEkle).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Liste"); } [HttpGet] public ActionResult TonerCikis(int? ID) { ViewBag.id = ID; //var YaziciModel = db.Yazicilar.Where(x => x.ZIMMET == true).Select(a => new //{ // Value = a.ID, // Text = a.SERINO var YaziciModel = db.Yazicilar.Where(x => x.ZIMMET == true).Select(a => new { Value = a.ID, Text = a.SERINO }).ToList(); //ViewBag.dgr1 = YaziciModel; //List<SelectListItem> birimler = (from i in db.Birimler.Where(i => i.DURUM == true).ToList() // select new SelectListItem // { // Text = i.BIRIMAD, // Value = i.ID.ToString(), // }).ToList(); //ViewBag.dgr2 = birimler; //List<SelectListItem> personeller = (from i in db.Personeller.Where(i => i.DURUM == true).ToList() // select new SelectListItem // { // Text = i.ADSOYAD, // Value = i.ID.ToString(), // }).ToList(); //ViewBag.dgr3 = personeller; List<SelectListItem> kullanici = (from i in db.Kullanicilar.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.ADISOYADI, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr4 = kullanici; //List<SelectListItem> yazicimarka = (from i in db.YaziciMarkalari.Where(i => i.DURUM == true).ToList() // select new SelectListItem // { // Text = i.YAZICIMARKA, // Value = i.ID.ToString(), // }).ToList(); //ViewBag.dgr5 = yazicimarka; //List<SelectListItem> yazicimodel = (from i in db.YaziciModelleri.Where(i => i.DURUM == true).ToList() // select new SelectListItem // { // Text = i.YAZICIMODEL, // Value = i.ID.ToString(), // }).ToList(); //ViewBag.dgr6 = yazicimodel; return View(); } [HttpPost] public ActionResult TonerCikis(TonerCikis toner) { if (ModelState.IsValid) { if (toner.TONERADET == null || toner.DRAMADET == null) { return View("TonerCikis"); } db.TonerCikis.Add(toner); var TonerCikar = db.TonerStok.FirstOrDefault(x => x.YAZICIMARKALARIID == toner.YAZICIMARKAID&& x.YAZICIMODELLERIID == toner.YAZICIMODELID); TonerCikar.KALANTONER -= toner.TONERADET; TonerCikar.KALANDRUM -= toner.DRAMADET; db.Entry(TonerCikar).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } return RedirectToAction("Liste"); } public ActionResult TonerStok() { var model = db.TonerStok.ToList(); return View(model); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class BirimController : Controller { // GET: Birim private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var liste = db.Birimler.Where(m => m.DURUM == true).ToList(); return View(liste); } [HttpGet] public ActionResult Ekle() { return View(); } [HttpPost] public ActionResult Ekle(Birimler p) { if (!ModelState.IsValid) { return View("Ekle"); } db.Birimler.Add(p); p.DURUM = true; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Sil(int id) { var bilgi = db.Birimler.Find(id); bilgi.DURUM = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Getir(int id) { var bilgi = db.Birimler.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Birimler p) { var bilgi = db.Birimler.Find(p.ID); bilgi.BIRIMAD= p.BIRIMAD; bilgi.DURUM = true; db.SaveChanges(); return RedirectToAction("Index"); } } }<file_sep>using BilgiIslemEnvanter.Models.Entity; using OfficeOpenXml; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace BilgiIslemEnvanter.Controllers { public class RaporlarController : Controller { private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] #region Zimmet Listesi public ActionResult ZimmetListesi() { var Model = db.Tasinirlar.Where(x => x.ZIMMET == true).ToList(); return View(Model); } public void ZimmetExcelAktar() { string constr = ConfigurationManager.AppSettings["connectionString"]; //var Client = new MongoClient(constr); //var db = Client.GetDatabase("Employee"); //var collection = db.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList(); var Model = db.Tasinirlar.Where(i=>i.ZIMMET == true).ToList(); ExcelPackage Ep = new ExcelPackage(); ExcelWorksheet Sheet = Ep.Workbook.Worksheets.Add("Report"); Sheet.Cells["A1"].Value = "AdSoyad"; Sheet.Cells["B1"].Value = "Domain-Adi"; Sheet.Cells["C1"].Value = "Domain-IP"; Sheet.Cells["D1"].Value = "Yazici-Port"; Sheet.Cells["E1"].Value = "Bilgisayar"; Sheet.Cells["F1"].Value = "Tarayici"; Sheet.Cells["G1"].Value = "Yazici"; int row = 2; foreach (var item in Model) { Sheet.Cells[string.Format("A{0}", row)].Value = item.Personeller.ADSOYAD; Sheet.Cells[string.Format("B{0}", row)].Value = item.DOMAINADI; Sheet.Cells[string.Format("C{0}", row)].Value = item.DOMAINIP; Sheet.Cells[string.Format("D{0}", row)].Value = item.YAZICIPORT; Sheet.Cells[string.Format("E{0}", row)].Value = item.Bilgisayarlar.SERINO + " - " + item.Bilgisayarlar.MARKA + " - " + item.Bilgisayarlar.MODEL; Sheet.Cells[string.Format("F{0}", row)].Value = item.Tarayicilar.SERINO + " - " + item.Tarayicilar.MARKA + " - " + item.Tarayicilar.MODEL; Sheet.Cells[string.Format("G{0}", row)].Value = item.Yazicilar.SERINO /*+ " - " + item.Yazicilar.YaziciMarkalari.YAZICIMARKA + " - " + item.Yazicilar.MODELID*/; row++; } Sheet.Cells["A:AZ"].AutoFitColumns(); Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment: filename=" + "Report.xlsx"); Response.BinaryWrite(Ep.GetAsByteArray()); Response.End(); } #endregion public ActionResult Getir(int id) { var bilgi = db.Tasinirlar.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Tasinirlar ta) { var bilgi = db.Tasinirlar.Find(ta.ID); bilgi.DOMAINADI = ta.DOMAINADI; bilgi.DOMAINIP = ta.DOMAINIP; bilgi.YAZICIPORT = ta.YAZICIPORT; db.SaveChanges(); return RedirectToAction("ZimmetListesi"); } public ActionResult DepoyaCek(int ID, bool? Bilgisayar, bool? Yazici, bool? Tarayici) { var bilgi1 = db.Tasinirlar.Find(ID); if (Bilgisayar == true) { var BilgisayarM = db.Bilgisayarlar.FirstOrDefault(x => x.ID == bilgi1.BILGISAYARID); BilgisayarM.ZIMMET = false; bilgi1.BILGIZIMMET = false; bilgi1.BILGISAYARID= 177; if (bilgi1.YAZICIID == 119 && bilgi1.TARAYICIID == 39) { bilgi1.YAZICIZIMMET = false; bilgi1.TARAYICIZIMMET = false; bilgi1.ZIMMET = false; } db.Entry(BilgisayarM).State = System.Data.Entity.EntityState.Modified; } if (Yazici == true) { var YaziciM = db.Yazicilar.FirstOrDefault(x => x.ID == bilgi1.YAZICIID); YaziciM.ZIMMET = false; bilgi1.YAZICIZIMMET = false; bilgi1.YAZICIID = 119; if (bilgi1.BILGISAYARID == 177 && bilgi1.TARAYICIID == 39 && bilgi1.YAZICIZIMMET == false) { bilgi1.TARAYICIZIMMET = false; bilgi1.BILGIZIMMET = false; bilgi1.ZIMMET = false; bilgi1.Yazicilar.PERSONELID= 176; bilgi1.Yazicilar.BIRIMID = 50; } db.Entry(YaziciM).State = System.Data.Entity.EntityState.Modified; } if (Tarayici == true) { var TarayiciM = db.Tarayicilar.FirstOrDefault(x => x.ID == bilgi1.TARAYICIID); TarayiciM.ZIMMET = false; bilgi1.TARAYICIZIMMET = false; bilgi1.TARAYICIID = 39; if (bilgi1.BILGISAYARID == 177 && bilgi1.YAZICIID == 119 && bilgi1.TARAYICIZIMMET == false) { bilgi1.YAZICIZIMMET = false; bilgi1.BILGIZIMMET = false; bilgi1.ZIMMET = false; } db.Entry(TarayiciM).State = System.Data.Entity.EntityState.Modified; } //şöyle bir şeyde olsa örneğin üçüde seçilmişse tasınırlar tablosundaki zimmet alanı false olsun, değilse true olmaya devam etsin.basit //o zaman alttaki işlevsiz kalacak. doğrumu yeni kod yazacağız. evete //var BilgiModel = db.Tasinirlar.FirstOrDefault(x => x.BILGISAYARID == x.Bilgisayarlar.ID); //var BilgiModel = db.Tasinirlar.FirstOrDefault(x => x.BILGISAYARID == ID); //BilgiModel.ZIMMET = false; if (Tarayici == true && Yazici == true && Bilgisayar == true) { var BilgiModel = db.Tasinirlar.FirstOrDefault(x => x.ID == ID); BilgiModel.ZIMMET = false; bilgi1.BILGIZIMMET = false; bilgi1.YAZICIZIMMET = false; bilgi1.TARAYICIZIMMET = false; var BilgisayarM = db.Bilgisayarlar.FirstOrDefault(x => x.ID == bilgi1.BILGISAYARID); BilgisayarM.ZIMMET = false; var TarayiciM = db.Tarayicilar.FirstOrDefault(x => x.ID == bilgi1.TARAYICIID); TarayiciM.ZIMMET = false; var YaziciM = db.Yazicilar.FirstOrDefault(x => x.ID == bilgi1.YAZICIID); YaziciM.ZIMMET = false; YaziciM.PERSONELID = 176; YaziciM.BIRIMID = 50; db.Entry(BilgiModel).State = System.Data.Entity.EntityState.Modified; db.Entry(BilgisayarM).State = System.Data.Entity.EntityState.Modified; db.Entry(YaziciM).State = System.Data.Entity.EntityState.Modified; db.Entry(TarayiciM).State = System.Data.Entity.EntityState.Modified; } //else //{ // var BilgiModel = db.Tasinirlar.FirstOrDefault(x => x.ID == ID); // BilgiModel.ZIMMET = true; // db.Entry(BilgiModel).State = System.Data.Entity.EntityState.Modified; //} db.SaveChanges(); return RedirectToAction("ZimmetListesi"); } public ActionResult TarihFiltre1() { return View(db.TonerCikis.ToList()); } [HttpPost] public ActionResult TarihFiltre1(DateTime start, DateTime end) { return View(db.GetFunctionTarihFiltresi(start, end)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class YaziciController : Controller { // GET: Yazici private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var listeleme = db.Yazicilar.Where(i=>i.DURUM==true).ToList(); //var liste = db.Yazicilar.Where(m => m.DURUM == true).ToList(); return View(listeleme); } [HttpGet] public ActionResult Ekle() { List<SelectListItem> degerler1 = (from i in db.YaziciMarkalari.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.YAZICIMARKA, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr1 = degerler1; List<SelectListItem> degerler2 = (from i in db.YaziciModelleri.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.YAZICIMODEL, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr2 = degerler2; return View(); } [HttpPost] public ActionResult Ekle(Yazicilar p) { if (!ModelState.IsValid) { return View("Ekle"); } p.DURUM = true; p.ZIMMET = false; p.BIRIMID = 50; p.PERSONELID = 176; db.Yazicilar.Add(p); db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Sil(int id) { var bilgi = db.Yazicilar.Find(id); bilgi.DURUM = false; bilgi.ZIMMET = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Getir(int id) { var bilgi = db.Yazicilar.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Yazicilar p) { var bilgi = db.Yazicilar.Find(p.ID); var yazicimarkasi= db.YaziciMarkalari.Where(m => m.ID == p.YaziciMarkalari.ID).FirstOrDefault(); bilgi.MARKAID= p.YaziciMarkalari.ID; var yazicimodels = db.YaziciModelleri.Where(m => m.ID == p.YaziciModelleri.ID).FirstOrDefault(); bilgi.MODELID = p.YaziciModelleri.ID; bilgi.MARKAID = p.MARKAID; bilgi.MODELID = p.MODELID; bilgi.SERINO = p.SERINO; bilgi.DURUM = true; bilgi.ZIMMET = false; db.SaveChanges(); return RedirectToAction("Index"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; using BilgiIslemEnvanter.MyClasses; namespace BilgiIslemEnvanter.Controllers { public class PersonelController : Controller { // GET: Personel private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var liste = db.Personeller.Where(m => m.DURUM == true).ToList(); return View(liste); } [HttpGet] public ActionResult Ekle() { List<SelectListItem> degerler1 = (from i in db.Unvanlar.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.UNVANAD, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr1 = degerler1; List<SelectListItem> degerler2 = (from i in db.Birimler.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.BIRIMAD, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr2 = degerler2; return View(); } [HttpPost] public ActionResult Ekle(Personeller p) { var unvan = db.Unvanlar.Where(m => m.ID == p.Unvanlar.ID).FirstOrDefault(); p.Unvanlar = unvan; var birim = db.Birimler.Where(m => m.ID == p.Birimler.ID).FirstOrDefault(); p.Birimler = birim; if (p.SICIL == null) { return View("Ekle"); } db.Personeller.Add(p); p.DURUM = true; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Sil(int id) { var bilgi = db.Personeller.Find(id); bilgi.DURUM = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Getir(int id) { List<SelectListItem> degerler1 = (from i in db.Unvanlar.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.UNVANAD, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr1 = degerler1; List<SelectListItem> degerler2 = (from i in db.Birimler.Where(i => i.DURUM == true).ToList() select new SelectListItem { Text = i.BIRIMAD, Value = i.ID.ToString(), }).ToList(); ViewBag.dgr2 = degerler2; var bilgi = db.Personeller.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Personeller p) { var bilgi = db.Personeller.Find(p.ID); bilgi.SICIL = p.SICIL; bilgi.ADSOYAD = p.ADSOYAD; bilgi.DAHILITELEFONU = p.DAHILITELEFONU; bilgi.CEPTELEFONU = p.CEPTELEFONU; bilgi.DURUM = true; var unvan = db.Unvanlar.Where(m => m.ID == p.Unvanlar.ID).FirstOrDefault(); bilgi.UNVANID = unvan.ID; var birim = db.Birimler.Where(m => m.ID == p.Birimler.ID).FirstOrDefault(); bilgi.BIRIMID = birim.ID; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult ZimmetYap(int? ID) { ViewBag.id = ID; var BilgisayarModel = db.Bilgisayarlar.Where(x => x.DURUM == true && x.ZIMMET == false && x.SERINO != "BAKANLIK").OrderByDescending(x => x.SERINO == null).Select(a => new { Value = a.ID, Text = a.SERINO + " -- " + a.MARKA + " -- " + a.MODEL }).ToList(); var YaziciModel = db.Yazicilar.Where(x => x.DURUM == true && x.ZIMMET == false).OrderByDescending(x => x.SERINO == null).Select( a => new { Value = a.ID, Text = a.SERINO + " -- " + a.YaziciMarkalari.YAZICIMARKA + " -- " + a.YaziciModelleri.YAZICIMODEL }).ToList(); var TarayiciModel = db.Tarayicilar.Where(x => x.DURUM == true && x.ZIMMET == false).OrderByDescending(x => x.SERINO == null).Select(a => new { Value = a.ID, Text = a.SERINO + " -- " + a.MARKA + " -- " + a.MODEL }).ToList(); ViewBag.tarayiciSN = new SelectList(TarayiciModel, "Value", "Text"); ViewBag.yaziciSN = new SelectList(YaziciModel, "Value", "Text"); ViewBag.BilgisayarSN = new SelectList(BilgisayarModel, "Value", "Text"); return View(); } [HttpPost] public ActionResult Zimmetle(HepiTopu hep) { var personel = hep.personelID; var yazici = hep.yaziciSN; var tarayici = hep.tarayiciSN; var bilgisayar = hep.bilgisayarSN; var domainadi = hep.domainAdi; var domainip = hep.domainIP; var yaziciip = hep.yaziciIP; var birim = hep.BirimID; hep.Durum = true; hep.Zimmet = true; Tasinirlar tasinir = new Tasinirlar { BILGISAYARID = bilgisayar, DOMAINADI = domainadi, DOMAINIP = domainip, PERSONELID = personel, TARAYICIID = tarayici, YAZICIID = yazici, YAZICIPORT = yaziciip, BIRIMID = birim, DURUM = true, ZIMMET = true, }; db.Tasinirlar.Add(tasinir); //Yazıcıyı Id ile buldu ve zimmet alanını true'ye çevirdi. var YaziciModel = db.Yazicilar.FirstOrDefault(x => x.ID == yazici); if (YaziciModel.SERINO == null) { YaziciModel.ZIMMET = false; } else { YaziciModel.ZIMMET = true; YaziciModel.PERSONELID = hep.personelID; YaziciModel.BIRIMID = hep.BirimID; } db.Entry(YaziciModel).State = System.Data.Entity.EntityState.Modified; //Bilgisayar Id ile buldu ve zimmet alanını true'ye çevirdi. var BilgiModel = db.Bilgisayarlar.FirstOrDefault(x => x.ID == bilgisayar); if (BilgiModel.SERINO == null) { BilgiModel.ZIMMET = false; } else { BilgiModel.ZIMMET = true; } db.Entry(BilgiModel).State = System.Data.Entity.EntityState.Modified; //Tarayıcı Id ile buldu ve zimmet alanını true'ye çevirdi. var TaraModel = db.Tarayicilar.FirstOrDefault(x => x.ID == tarayici); if (TaraModel.SERINO == null) { TaraModel.ZIMMET = false; } else { TaraModel.ZIMMET = true; } db.Entry(TaraModel).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; using Microsoft.Ajax.Utilities; namespace BilgiIslemEnvanter.Controllers { public class HomeController : Controller { private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var liste = db.TonerCikis.ToList(); var kalantonerms510 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 6).Sum(stok => stok.KALANTONER); ViewBag.dgr1 = kalantonerms510; var kalandrumms510= db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 6).Sum(stok => stok.KALANDRUM); ViewBag.dgr2 = kalandrumms510; var kalantonerms810 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 7).Sum(stok => stok.KALANTONER); ViewBag.dgr3 = kalantonerms810; var kalandrumms810 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 7).Sum(stok => stok.KALANDRUM); ViewBag.dgr4 = kalandrumms810; var kalantonert650= db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 10).Sum(stok => stok.KALANTONER); ViewBag.dgr5 = kalantonert650; var kalantonerms823 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 8).Sum(stok => stok.KALANTONER); ViewBag.dgr6 = kalantonerms823; //var depopcsayisi = db.Bilgisayarlar.Where(i => i.ZIMMET == false).Count()-1; //ViewBag.dgr1 = depopcsayisi; //var yazicisayisi = db.Yazicilar.Where(i => i.ZIMMET == false).Count()-1; //ViewBag.dgr2 = yazicisayisi; //var tarayicisayisi = db.Tarayicilar.Where(i => i.ZIMMET == false).Count()-1; //ViewBag.dgr3 = tarayicisayisi; var kalantonermx710 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 9).Sum(stok => stok.KALANTONER); ViewBag.dgr7 = kalantonermx710; var kalandrummx710 = db.TonerStok.Where(i => i.YAZICIMARKALARIID == 1 && i.YAZICIMODELLERIID == 9).Sum(stok => stok.KALANDRUM); ViewBag.dgr8 = kalandrummx710; return View(liste); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class UnvanController : Controller { // GET: Unvan private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var liste = db.Unvanlar.Where(m => m.DURUM == true).ToList(); return View(liste); } [HttpGet] public ActionResult Ekle() { return View(); } [HttpPost] public ActionResult Ekle(Unvanlar p) { if (!ModelState.IsValid) { return View("Ekle"); } db.Unvanlar.Add(p); p.DURUM = true; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Sil(int id) { var bilgi = db.Unvanlar.Find(id); bilgi.DURUM = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Getir(int id) { var bilgi = db.Unvanlar.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Unvanlar p) { var bilgi = db.Unvanlar.Find(p.ID); bilgi.UNVANAD= p.UNVANAD; bilgi.DURUM = true; db.SaveChanges(); return RedirectToAction("Index"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class LoginController : Controller { // GET: Login private BilgiIslemEntities2 db = new BilgiIslemEntities2(); public ActionResult GirisYap() { return View(); } [HttpPost] public ActionResult GirisYap(Kullanicilar p) { var bilgiler = db.Kullanicilar.FirstOrDefault(x => x.SICIL == p.SICIL&& x.SIFRE == p.SIFRE); if (bilgiler != null) { FormsAuthentication.SetAuthCookie(bilgiler.SICIL, false); Session["SICIL"] = bilgiler.SICIL.ToString(); return RedirectToAction("Index", "Home"); } else { return View(); } } public ActionResult CikisYap() { FormsAuthentication.SignOut(); return RedirectToAction("GirisYap", "Login"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BilgiIslemEnvanter.MyClasses { public class HepiTopu { public int personelID { get; set; } public int bilgisayarSN { get; set; } public int yaziciSN { get; set; } public int tarayiciSN { get; set; } public string domainAdi { get; set; } public string domainIP { get; set; } public string yaziciIP { get; set; } public bool Durum { get; set; } public bool Zimmet { get; set; } public int BirimID { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class TasinirController : Controller { // GET: Tasinir private BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Liste() { var liste = db.Personeller.Where(m => m.DURUM == true).ToList(); return View(liste); } public ActionResult FisDuzenle() { return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BilgiIslemEnvanter.Models.Entity; namespace BilgiIslemEnvanter.Controllers { public class BilgisayarController : Controller { // GET: Bilgisayar public BilgiIslemEntities2 db = new BilgiIslemEntities2(); [Authorize] public ActionResult Index() { var bilgisayarlar = db.Bilgisayarlar.Where(m => m.DURUM == true && m.SERINO!="BAKANLIK").ToList(); return View(bilgisayarlar); } [HttpGet] public ActionResult Ekle() { return View(); } [HttpPost] public ActionResult Ekle(Bilgisayarlar p) { if (!ModelState.IsValid) { return View("Ekle"); } db.Bilgisayarlar.Add(p); p.DURUM = true; p.ZIMMET = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Sil(int id) { var bilgi = db.Bilgisayarlar.Find(id); bilgi.DURUM = false; bilgi.ZIMMET = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Getir(int id) { var bilgi = db.Bilgisayarlar.Find(id); return View("Getir", bilgi); } public ActionResult Guncelle(Bilgisayarlar p) { var bilgi = db.Bilgisayarlar.Find(p.ID); bilgi.MARKA = p.MARKA; bilgi.MODEL = p.MODEL; bilgi.SERINO = p.SERINO; bilgi.DURUM = true; bilgi.ZIMMET = false; db.SaveChanges(); return RedirectToAction("Index"); } } }<file_sep>var logIn = $("#login"); var signUp = $("#signup"); var menu = $("#menu ul"); $("#log").on("click", function(e) { e.preventDefault(); //Set active link $(this).addClass("active a"); $("#sign").removeClass("active a"); //Set animation logIn.toggleClass("active"); signUp.toggleClass("active"); menu.toggleClass("nextBox"); }); $("#sign").on("click", function(e) { e.preventDefault(); //Set active link $(this).addClass("active a"); $("#log").removeClass("active a"); //Set animation signUp.toggleClass("active"); logIn.toggleClass("active"); menu.toggleClass("nextBox"); });
0b34f6aa0de3162bdc0ddc3de62218b496fa7c92
[ "JavaScript", "C#" ]
13
C#
adaletinsesi1515/BilgiIslemEnvanters
609c9a8f10833dcf803d18a831712d8eb1e66dbd
df9d0870d56481f7582cba5ad54f7306d75394e1
refs/heads/main
<file_sep><?php require("dbconnect.php"); $title=mysqli_real_escape_string($conn,$_POST['title']); // 轉換字符串中特殊字符 $content=mysqli_real_escape_string($conn,$_POST['content']); // $_POST: 接收使用者傳送的資料 $assignee=mysqli_real_escape_string($conn,$_POST['assignee']); $emergencylevel=mysqli_real_escape_string($conn,$_POST['emergencylevel']); $status=mysqli_real_escape_string($conn,$_POST['status']); if ($title) { //if title is not empty $sql = "insert into todo (title, content, assignee, emergencylevel, status) values ('$title', '$content', '$assignee', '$emergencylevel','$status');"; mysqli_query($conn, $sql) or die("Insert failed, SQL query error"); //執行SQL $msg = "Message added"; } else { $msg = "Message title cannot be empty"; } header("location: listTodo.php?m={$msg}"); ?> <a href="listTodo.php">Back</a>;<file_sep><?php require("dbconnect.php"); $msgID=(int)$_POST['id']; if ($msgID) { $sql = "delete from todo where id=$msgID;"; mysqli_query($conn,$sql) or die("MySQL query error"); //執行SQL $msg = "Message deleted."; } header("location: listTodo.php?m={$msg}"); ?> <a href="listTodo.php">Back</a>; <file_sep><?php session_start(); require("dbconnect.php"); $title=mysqli_real_escape_string($conn,$_POST['title']); // 轉換字符串中特殊字符 $content=mysqli_real_escape_string($conn,$_POST['content']); // $_POST: 接收使用者傳送的資料 $assignee=mysqli_real_escape_string($conn,$_POST['assignee']); $emergencylevel=mysqli_real_escape_string($conn,$_POST['emergencylevel']); $status=mysqli_real_escape_string($conn,$_POST['status']); $one = $_SESSION['one']; if ($one) { $sql = "update todo set title='$title', content='$content', assignee='$assignee', emergencylevel='$emergencylevel', status='$status' where id=$one;"; mysqli_query($conn,$sql) or die("MySQL query error"); //執行SQL $msg = "Message update"; } // echo "Modify completed."; header("location: listTodo.php?m={$msg}"); ?> <a href="listTodo.php">Back</a>;<file_sep><?php session_start(); // 通常如果你的網站具有會員登入的功能或是購物車的功能,基本上就可以使用到 session 來幫助你記錄這些資訊。 require("dbconnect.php"); if (isset($_GET['m'])){ $text = $_GET['m']; $msg = "<font color='red' size='40'>$text</font>"; // $msg = "<font color='red' size='40'>" . $_GET['m'] . "</font>; } else { $msg = "<font color='blue'>Good morning</font>"; } $sql = "select * from todo where status = 1 ORDER BY title, emergencylevel;"; $result=mysqli_query($conn,$sql) or die("DB Error: Cannot retrieve message."); // 執行查詢,mysqli_query(使用的mysql連接, 查詢字符串) ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>工作清單</title> </head> <body> <p>Completed Task !! </p> <p><?php echo $msg;?></P> <hr /> <table width="200" border="1"> <tr> <td>id</td> <td>title</td> <td>content</td> <td>Assignee</td> <td>Emergencylevel</td> <td>status</td> </tr> <?php $count = 0; while ( $rs=mysqli_fetch_assoc($result)) { // 從結果集中取得一行作為關聯組數,類似去抓取這個資料表哪個欄位 echo "<tr><td>" . $rs['id'] . "</td>"; // 這邊就是去抓取id欄位 echo "<td>{$rs['title']}</td>"; echo "<td>" , $rs['content'], "</td>"; echo "<td>" , $rs['assignee'], "</td>"; //echo "<font color=red>".$num."</font>"; //echo "<td>" , $rs['emergencylevel'], "</td>"; if ($rs['emergencylevel']=="3High"){ echo "<td><font color=red>" .$rs['emergencylevel']. "</font></td>"; } else if ($rs['emergencylevel']=="2Medium"){ echo "<td><font color=blue>" .$rs['emergencylevel']. "</font></td>"; } if ($rs['emergencylevel']=="1Low"){ echo "<td><font color=black>" .$rs['emergencylevel']. "</font></td>"; } echo "<td>" . $rs['status'], "</td>"; echo "<td>", "<a href = 'Return.php?id={$rs['id']}'>Return</a>", "</td>"; echo "<td>", "<a href = 'End.php?id={$rs['id']}'>OK</a>", "</td>"; //echo "<td>", "<a href = 'ModifyMessageForm.php?id={$rs['id']}'>Modify</a>" . "</td></tr>"; $count = $count + 1; } //另外一種算幾筆的方法,用sql算! // $sql = "select count(*) as c from todo where status = 1;"; // $result = mysqli_query($conn,$sql); // $rs = mysqli_fetch_assoc($result); // echo "count(*)={$rs['c']} i=$i"; ?> </table> <!--<a href="addMessageForm.php">Add Message</a> <a href="deleteMessageForm.php">Delete Message</a>--> <p><?php echo "已完成 $count 項工作" ;?></P> <a href="listTodo.php">Back</a>; </body> </html> <file_sep><?php session_start(); // 通常如果你的網站具有會員登入的功能或是購物車的功能,基本上就可以使用到 session 來幫助你記錄這些資訊。 require("dbconnect.php"); $sql = "select * from todo where status = 0 ORDER BY title, emergencylevel;"; $result=mysqli_query($conn,$sql) or die("DB Error: Cannot retrieve message."); // 執行查詢,mysqli_query(使用的mysql連接, 查詢字符串) ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>工作清單</title> </head> <body> <p>未完成! </p> <hr /> <table width="200" border="1"> <tr> <td>id</td> <td>title</td> <td>content</td> <td>Assignee</td> <td>Emergencylevel</td> <td>status</td> </tr> <?php while ( $rs=mysqli_fetch_assoc($result)) { // 從結果集中取得一行作為關聯組數,類似去抓取這個資料表哪個欄位 echo "<tr><td>" . $rs['id'] . "</td>"; // 這邊就是去抓取id欄位 echo "<td>{$rs['title']}</td>"; echo "<td>" , $rs['content'], "</td>"; echo "<td>" , $rs['assignee'], "</td>"; if ($rs['emergencylevel']=="3High"){ echo "<td><font color=red>" .$rs['emergencylevel']. "</font></td>"; } else if ($rs['emergencylevel']=="2Medium"){ echo "<td><font color=blue>" .$rs['emergencylevel']. "</font></td>"; } if ($rs['emergencylevel']=="1Low"){ echo "<td><font color=black>" .$rs['emergencylevel']. "</font></td>"; } echo "<td>" . $rs['status'], "</td>"; } ?> </table> <?php require("dbconnect.php"); $sql = "select * from todo where status = 1 ORDER BY title, emergencylevel;"; $result=mysqli_query($conn,$sql) or die("DB Error: Cannot retrieve message."); // 執行查詢,mysqli_query(使用的mysql連接, 查詢字符串) ?> <p>已完成!</p> <hr/> <table width="200" border="1"> <tr> <td>id</td> <td>title</td> <td>content</td> <td>Assignee</td> <td>Emergencylevel</td> <td>status</td> </tr> <?php while ( $rs=mysqli_fetch_assoc($result)) { // 從結果集中取得一行作為關聯組數,類似去抓取這個資料表哪個欄位 echo "<tr><td>" . $rs['id'] . "</td>"; // 這邊就是去抓取id欄位 echo "<td>{$rs['title']}</td>"; echo "<td>" , $rs['content'], "</td>"; echo "<td>" , $rs['assignee'], "</td>"; if ($rs['emergencylevel']=="3High"){ echo "<td><font color=red>" .$rs['emergencylevel']. "</font></td>"; } else if ($rs['emergencylevel']=="2Medium"){ echo "<td><font color=blue>" .$rs['emergencylevel']. "</font></td>"; } if ($rs['emergencylevel']=="1Low"){ echo "<td><font color=black>" .$rs['emergencylevel']. "</font></td>"; } echo "<td>" . $rs['status'], "</td>"; } ?> </table> <a href="Employee.php">Employee</a> <a href="listTodo.php">Boss</a> </body> </html> <file_sep><?php session_start(); // 通常如果你的網站具有會員登入的功能或是購物車的功能,基本上就可以使用到 session 來幫助你記錄這些資訊。 require("dbconnect.php"); $msgID=(int)$_GET['id']; $_SESSION['one']=$msgID; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>修改工作</title> </head> <body> <h1>Modify Message</h1> <form method="post" action="ModifyMessage.php"> <!--action = 使用者按下送出後資料會傳去哪--> Title: <input name="title" type="text" id="title" /> <br> Content: <input name="content" type="text" id="content" /> <br> Assignee: <input name="assignee" type="text" id="assignee" /> <br> Emergencylevel: <input name="emergencylevel" type="radio" id="emergencylevel" value="3High"/> High <input name="emergencylevel" type="radio" id="emergencylevel" value="2Medium"/> Medium <input name="emergencylevel" type="radio" id="emergencylevel" value="1Low" checked/> Low<br> Status: <input name="status" type="radio" id="status" value="0" checked/>0 <input name="status" type="radio" id="status" value="1" />1 <br> <input type="submit" name="Submit" value="送出" /> </form> </tr> </table> <a href="listTodo.php">Back</a>; </body> </html><file_sep><?php session_start(); // 通常如果你的網站具有會員登入的功能或是購物車的功能,基本上就可以使用到 session 來幫助你記錄這些資訊。 require("dbconnect.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>新增工作</title> </head> <body> <h1>Add New Message</h1> <form method="post" action="addMessage.php"> <!--action = 使用者按下送出後資料會傳去哪--> Title: <input name="title" type="text" id="title" /> <br> <!--表單會傳value值過去,若是沒設定,value就是你打的東西--> Content: <input name="content" type="text" id="content" /> <br> Assignee: <input name="assignee" type="text" id="assignee" /> <br> Emergencylevel: <input name="emergencylevel" type="radio" id="emergencylevel" value="3High" /> High <input name="emergencylevel" type="radio" id="emergencylevel" value="2Medium"/> Medium <input name="emergencylevel" type="radio" id="emergencylevel" value="1Low" checked/> Low<br> Status: <input name="status" type="radio" id="status" value="0" checked/>0 <br> <input type="submit" name="Submit" value="送出" /> </form> </tr> </table> <a href="listTodo.php">Back</a>; </body> </html> <file_sep><?php session_start(); // 通常如果你的網站具有會員登入的功能或是購物車的功能,基本上就可以使用到 session 來幫助你記錄這些資訊。 require("dbconnect.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>修改工作</title> </head> <body> <h1>Modify Message</h1> <form method="post" action="ModifyMessage.php"> <!--action = 使用者按下送出後資料會傳去哪--> Title: <input name="title" type="text" id="title" /> <br> COntent: <input name="content" type="text" id="content" /> <br> Status: <input name="status" type="text" id="status" /> <br> <input type="submit" name="Submit" value="送出" /> </form> </tr> </table> <a href="listTodo.php">Back</a>; </body> </html>
d0161ffed54f0d73e48eabdd7cd4ab48d0e8d8d2
[ "PHP" ]
8
PHP
jasonchang1126/test1
afb0d95eca1b65f2003abca9f2a296352d4511b3
8a2650e31729cf1398be82afe2ab6ded32f0ca0e
refs/heads/master
<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const Promise = require('bluebird'); var request = Promise.promisifyAll(require( "request"), { multiArgs: true }); const app = express(); app.use(bodyParser.raw()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const charactersJSON = require('./resources/characters'); app.get('/characters', (req, res) => { res.status(200).json(charactersJSON); }); app.get('/:character/films', (req, res) => { // Find character entry in characters.json const matchingCharacters = charactersJSON.characters.filter(character => { return character.name.toLowerCase() === req.params.character.toLowerCase(); }); if(matchingCharacters.length === 1){ const character = matchingCharacters[0]; request(character.url, function (error, response, body) { if (error) { res.status(500).send("Sorry, an error occurred.") } let filmURLs = JSON.parse(body).films; if(!filmURLs){ res.status(500).send("Sorry, an error occurred.") } Promise.map(filmURLs, filmURL => { // Bluebird / Request boilerplate code return request.getAsync(filmURL).spread(function(response,body) { return [JSON.parse(body)]; }); }).then(results => { results = results.map(result => { result = result[0]; const releaseDate = new Date(result['release_date'] + 'EST'); const dateOptions = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' } const filmSimple = { title: result['title'], releaseDate: releaseDate.toLocaleString("en-US", dateOptions) } return filmSimple; }); res.send({ character: character.name, movies: results }); }); }) }else { res.status(400).send("Character not found.") } }); app.listen(process.env.PORT || 3001);<file_sep>import React, {Component} from 'react'; import PropTypes from 'prop-types' import '../pages/App.css'; import Button from '@material-ui/core/Button' class Character extends Component{ render(){ return ( <li class="character" onClick={this.getMovies.bind(this)}> <Button variant="contained" color="primary"> {this.props.characterDetails.name} </Button> </li> ); } getMovies(e){ e.preventDefault(); this.props.getMovies(this.props.characterDetails.name); } }; Character.propTypes = { characterDetails: PropTypes.object, getMovies: PropTypes.func } export default Character;<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware, combineReducers } from 'redux'; import { loading } from './reducers/loading'; import { errors } from './reducers/errors'; import { characters } from './reducers/characters'; import { movies } from './reducers/movies'; import characterService from './service/characterService' import App from './pages/App'; const rootReducer = combineReducers({ characters, movies, loading, errors }); const store = createStore(rootReducer, {}, applyMiddleware(characterService)); const Root = () => ( <Provider store={store}> <App /> </Provider> ) ReactDOM.render(<Root />, document.getElementById('root')); store.dispatch({type: 'GET_CHARACTERS'}); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); <file_sep>import request from 'superagent'; // Will be used for accessing SWAPI const characterService = store => next => action => { next(action); switch (action.type) { case 'GET_CHARACTERS': request .get('/characters') .end( (err, res) => { if(err){ next({ type: 'GET_CHARACTERS_ERROR', err }) } const data = JSON.parse(res.text).characters; next({ type: 'GET_CHARACTERS_RECEIVED', data }); }); break; case 'GET_MOVIES': const character = action.character; request .get(`/${character}/films`) .end( (err, res) => { if(err){ next({ type:'GET_MOVIES_ERROR', err }) } const data = JSON.parse(res.text); next({ type: 'GET_MOVIES_RECEIVED', data }) }); break; default: break; } }; export default characterService;<file_sep>export const characters = (state = [], action) => { switch (action.type) { case 'GET_CHARACTERS_RECEIVED': return action.data; default: return state; } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import './App.css'; import Character from "../components/Character"; import Movie from "../components/Movie"; import Grid from '@material-ui/core/Grid' const mapStateToProps = function(state){ return { loading: state.loading, characters: state.characters, movies: state.movies, errors: state.errors, } }; const mapDispatchToProps = function(dispatch){ return { getMovies: character => dispatch({type: 'GET_MOVIES', character: character}), } } class App extends Component { render() { return ( <Grid id="app" container direction="column" > {this.props.loading ? "Loading..." : ""} <div> <h1>Characters</h1> <ul id="characters"> {this.props.characters.map(character => <Character characterDetails={character} getMovies={this.props.getMovies} /> )} </ul> </div> { !this.props.errors && this.props.movies.movies && this.props.movies.movies.length > 0 && <div> <h1>Movies featuring {this.props.movies.character} </h1> <ul id="movies"> {this.props.movies.movies.map(movie => <Movie movieDetails={movie} />)} </ul> </div> } {this.props.errors && <p>An error has occurred.</p> } </Grid> ) } } export default connect(mapStateToProps, mapDispatchToProps)(App)<file_sep>import React, {Component} from 'react'; import PropTypes from 'prop-types' import '../pages/App.css'; class Movie extends Component{ render(){ return ( <li class="movie"> <p><b>{this.props.movieDetails.title}</b></p> <p>{this.props.movieDetails.releaseDate}</p> </li> ); } }; Movie.propTypes = { movieDetails: PropTypes.object, } export default Movie;
f67d1c01c36a8c378bbb84d9e0e2944559bf6772
[ "JavaScript" ]
7
JavaScript
saiftase/sw-character-appearance-tracker
11545061cc0c17541f42de209b3dd11e828b0e2f
d29871272415314a662524d8f58cb3e01da28c06
refs/heads/master
<repo_name>zhangdexing/StudentManagementSystem<file_sep>/main.c #include "head.h" //info_t array[5]; int tmp=0; int i,j,flag2,mode,student_num,elect; info_t *p; info_t *q; info_t str_tmp; int main(int argc, char const *argv[]) { //q=malloc(sizeof(int)*4); p=malloc(sizeof(info_t)*6); if (p ==NULL) { printf("full~\n"); return -1; } while(1) { printf(""YELLOW"======================================================================\n"); printf(""RED"请输入你的模式[1]增加[2]显示[3]修改[4]删除[5]筛选模式[6]退出:"YELLOW" \n"); printf("======================================================================\n"); while ( scanf("%d",&mode) != 1) { printf("**********************************************************************\n"); printf(" 请正确输入对应模式的“数字”!\n"); while(getchar() != '\n'); printf("**********************************************************************\n"); } printf("======================================================================\n"); system("clear"); if (mode==6) { printf("============================\n"); printf(" 已退出!~\n"); printf("============================\n"); break; } call_back(mode-1); /*switch(mode) { case 1: if (tmp > 4) { printf("**********************************************************************\n"); printf(" 无法增加,管理系统信息表格已经填满!\n"); printf("**********************************************************************\n"); break; } func_case1( ); break; case 2: func_case2(); break; case 3: func_case3(); break; case 4: func_case4(); break; case 5: func_case6(); break; case 6: flag2=1; printf("============================\n"); printf(" 已退出!~\n"); printf("============================\n"); break; default: printf("============================\n"); printf(" 输入模式有误!~\n"); printf("============================\n"); }*/ } free(p); free(q); return 0; } <file_sep>/color.c #defineNONE "\033[m" #defineRED "\033[0;32;31m" //0表示厚度 #defineLIGHT_RED "\033[1;31m" #defineGREEN "\033[0;32;32m" #defineLIGHT_GREEN "\033[1;32m" #defineBLUE "\033[0;32;34m" #defineLIGHT_BLUE "\033[1;34m" #defineDARY_GRAY "\033[1;30m" #defineCYAN "\033[0;36m" #defineLIGHT_CYAN "\033[1;36m" #definePURPLE "\033[0;35m" #defineLIGHT_PURPLE "\033[1;35m" #defineBROWN "\033[0;33m" #define YELLOW "\033[1;33m" #defineLIGHT_GRAY "\033[0;37m" #defineWHITE "\033[1;37m" #defineNONE "\033[m" #defineRED "\033[0;32;31m" #defineLIGHT_RED "\033[1;31m" #defineGREEN "\033[0;32;32m" #define LIGHT_GREEN "\033[1;32m" #defineBLUE "\033[0;32;34m" #defineLIGHT_BLUE "\033[1;34m" #defineDARY_GRAY "\033[1;30m" #defineCYAN "\033[0;36m" #defineLIGHT_CYAN "\033[1;36m" #definePURPLE "\033[0;35m" #defineLIGHT_PURPLE "\033[1;35m" #defineBROWN "\033[0;33m" #defineYELLOW "\033[1;33m" #defineLIGHT_GRAY "\033[0;37m" #defineWHITE "\033[1;37m"<file_sep>/callback.h #ifndef __CALLBACK_H__ #define __CALLBACK_H__ extern void func_case1( ); extern void func_case2( ); extern void func_case3( ); extern void func_case4( ); extern void func_case5( ); #endif<file_sep>/Makefile TARGET = 1 #OBJ = main.o func.o SRC = main.c func.c callback.c GCC_TOOL = gcc #$(BOJ):$(SRC) # $(GCC_TOOL) $(SRC) -c -o $(OBJ) -Wall $(TARGET):$(SRC) $(GCC_TOOL) $(SRC) -o $(TARGET) -Wall %.o:%.c $(GCC_TOOL) -o $@ $^ clean: rm $(TARGET) *.o <file_sep>/head.h #ifndef __HEAD_H__ #define __HEAD_H__ #include "stdio.h" #include "string.h" #include "stdlib.h" #include "stdbool.h" #include "string.h" #define NONE "\033[m"//结束符 #define YELLOW "\033[1;33m" //黄色 #define RED "\033[0;32;31m"//红色 #define WRITE "\033[1;37m"//白色 typedef struct info { char name[22]; unsigned char age; }info_t; extern int tmp; extern int i,j,flag2,mode,student_num,elect; extern info_t *p; extern info_t *q; extern info_t str_tmp; //extern info_t change; //extern info_t array[5]; extern void call_back( ); #endif<file_sep>/callback.c #include "callback.h" typedef void (*new_type)(void); new_type arr[6]={func_case1,func_case2,func_case3,func_case4,func_case5}; void call_back(int mode) { arr[mode]( ); }
030395cd983a2229d14ce307725a4523be490c4e
[ "C", "Makefile" ]
6
C
zhangdexing/StudentManagementSystem
2e761ddc5cf51eb006ff0d155f9d6f58d12b074a
59b6060c4daa49cd4bdf3c570a12ece1c0569f59
refs/heads/master
<repo_name>Strider2009/Arduino-TestProjects<file_sep>/bit_reg/bitShift_MotorControl/bitShift_MotorControl/bitShift_MotorControl.ino //**************************************************************// // Name : shiftOutCode, Hello World // Author : <NAME>,<NAME>, <NAME> // Date : 25 Oct, 2006 // Modified: 23 Mar 2010 // Version : 2.0 // Notes : Code for using a 74HC595 Shift Register // // : to count from 0 to 255 //**************************************************************** //Pin connected to ST_CP of 74HC595 int latchPin = 8; //Pin connected to SH_CP of 74HC595 int clockPin = 12; ////Pin connected to DS of 74HC595 int dataPin = 11; byte leds = 0; void setup() { //set pins to output so you can control the shift register pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); } void loop() { bitClear(leds); bitSet(leds, 1); updateShiftRegister(); delay(2000); bitClear(leds); bitSet(leds, 0); updateShiftRegister(); } } void updateShiftRegister() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, leds); digitalWrite(latchPin, HIGH); } <file_sep>/ESP8266/MQTT/MQTT.ino /* To upload through terminal you can use: curl -F "image=@firmware.bin" esp8266-webupdate.local/update */ #include <ESP8266WiFi.h> #include <Wire.h> #include <PubSubClient.h> #include "DHT.h" const char* host = "esp8266-webupdate"; #define wifi_ssid "ssid" #define wifi_password "<PASSWORD>" #define mqtt_server "192.168.0.12" #define humidity_topic "lr/hum" #define temperature_topic "lr/temp" WiFiClient espClient; PubSubClient client(espClient); #define DHTPIN 2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); void setup(void){ Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); // Set SDA and SDL ports Wire.begin(2, 14); dht.begin(); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect // If you do not want to use a username and password, change next line to if (client.connect("ESP8266Client_LIVINGROOM")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } bool checkBound(float newValue, float prevValue, float maxDiff) { return !isnan(newValue) && (newValue < prevValue - maxDiff || newValue > prevValue + maxDiff); } long lastMsg = 0; float temp = 0.0; float hum = 0.0; float diff = 1.0; void loop() { if (!client.connected()) { reconnect(); } client.loop(); delay(2000); Serial.println("looking for new temps..."); float newTemp = dht.readTemperature(); float newHum = dht.readHumidity(); Serial.println("Temperature: "); Serial.print(newTemp); if (checkBound(newTemp, temp, diff)) { temp = newTemp; Serial.println("New temperature: "); Serial.print(temp); client.publish(temperature_topic, String(temp).c_str(), true); } if (checkBound(newHum, hum, diff)) { hum = newHum; Serial.print("New humidity:"); Serial.println(String(hum).c_str()); client.publish(humidity_topic, String(hum).c_str(), true); } } <file_sep>/H-Bridge/l293d_owiRobotArm/robotArm/robotArm.ino int lmp1 = 13; int lmg1 = 12; int lmp2 = 11; int lmg2 = 10; int lmp3 = 9; int lmg3 = 8; int lmp4 = 7; int lmg4 = 6; void setup() { // put your setup code here, to run once: pinMode(lmp1, OUTPUT); pinMode(lmg1, OUTPUT); pinMode(lmp2, OUTPUT); pinMode(lmg2, OUTPUT); pinMode(lmp3, OUTPUT); pinMode(lmg3, OUTPUT); pinMode(lmp4, OUTPUT); pinMode(lmg4, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(lmp1,HIGH); digitalWrite(lmg1,LOW); digitalWrite(lmp2,HIGH); digitalWrite(lmg2,LOW); digitalWrite(lmp3,HIGH); digitalWrite(lmg3,LOW); digitalWrite(lmp4,HIGH); digitalWrite(lmg4,LOW); delay(3000); digitalWrite(lmp1,LOW); digitalWrite(lmg1,HIGH); digitalWrite(lmp2,LOW); digitalWrite(lmg2,HIGH); digitalWrite(lmp3,LOW); digitalWrite(lmg3,HIGH); digitalWrite(lmp4,LOW); digitalWrite(lmg4,HIGH); delay(5000); }
e25a7b073de1a10423b25601a1c71b81ad3d06a7
[ "C++" ]
3
C++
Strider2009/Arduino-TestProjects
0ac3bf8ceb086fb84a6d4a56fc0911a5168b1fc3
a9b8269f0b28f5a38f5a0f364f25d1cf05a89f00
refs/heads/master
<repo_name>skorulis/drone1-gdx<file_sep>/drone1/src/com/skorulis/camera/IsoFollowCamera.java package com.skorulis.camera; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector3; import com.skorulis.drone1.scene.SceneNode; public class IsoFollowCamera { private SceneNode item; private Camera cam; public IsoFollowCamera(SceneNode item) { this.item = item; resizeViewport(); } public void resizeViewport() { cam = new OrthographicCamera(20, 20 * Gdx.graphics.getHeight() / Gdx.graphics.getWidth()); cam.near = 0.1f; cam.far = 100f; } public void update(float delta) { Vector3 pos = item.absTransform().getTranslation(new Vector3()); cam.position.set(pos.x+5, 5, pos.z+5); cam.direction.set(-1, -1, -1); cam.update(); } public Camera cam() { return cam; } } <file_sep>/drone1/src/com/skorulis/drone1/def/BaseDef.java package com.skorulis.drone1.def; import java.util.ArrayList; public abstract class BaseDef { public String name; public abstract ArrayList<String> allModels(); } <file_sep>/drone1/src/com/skorulis/drone1/def/HullDef.java package com.skorulis.drone1.def; import java.util.ArrayList; import java.util.Arrays; import com.badlogic.gdx.math.Vector3; public class HullDef extends BaseDef { public String modelName; public ArrayList<TurretPointDef> turretPoints; public HullDef() { turretPoints = new ArrayList<TurretPointDef>(); } public ArrayList<String> allModels() { return new ArrayList<String>(Arrays.asList(modelName)); } public void addTurretPoint(Vector3 position, float size) { turretPoints.add(new TurretPointDef(position,size)); } public int maxTurrets() { return turretPoints.size(); } } <file_sep>/drone1/src/com/skorulis/drone1/scene/SceneNode.java package com.skorulis.drone1.scene; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.math.Matrix4; public interface SceneNode { public Matrix4 absTransform(); public Matrix4 relTransform(); public void render(ModelBatch batch, Environment environment); } <file_sep>/README.md drone1-gdx ========== Initial repository for my drone game created using gdx. Currently just an experiment using libgdx <file_sep>/drone1/src/com/skorulis/drone1/MyGdxGame.java package com.skorulis.drone1; import java.util.ArrayList; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.FPSLogger; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.skorulis.camera.IsoFollowCamera; import com.skorulis.camera.IsoPanCamera; import com.skorulis.drone1.def.DefManager; import com.skorulis.drone1.level.GameLevel; import com.skorulis.drone1.player.Player; import com.skorulis.drone1.unit.DroneUnit; public class MyGdxGame implements ApplicationListener { public IsoPanCamera isoCam; public ModelInstance instance; public ModelBatch modelBatch; public Environment environment; public FPSLogger fpsLogger; public AssetManager assets; public boolean loading; public DefManager defManager; public DroneUnit unit, unit2; public GameLevel level; public float t = 0; public Player player; @Override public void create() { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); defManager = new DefManager(); unit = new DroneUnit(defManager.getUnit("unit1")); unit2 = new DroneUnit(defManager.getUnit("unit1")); unit2.target = unit; unit.target = unit2; level = new GameLevel(25,25); assets = new AssetManager(); ArrayList<String> models = new ArrayList<String>(); models.addAll(unit.def.allModels()); for(String s : models) { assets.load(s, Model.class); } loading = true; fpsLogger = new FPSLogger(); player = new Player(unit); //isoCam = new IsoFollowCamera(unit); isoCam = new IsoPanCamera(); Gdx.input.setInputProcessor(isoCam); } private void doneLoading() { unit.setup(assets); unit2.setup(assets); unit.absTransform().setTranslation(level.center()); loading = false; } @Override public void dispose() { modelBatch.dispose(); level.dispose(); assets.clear(); } @Override public void render() { if(loading) { if(assets.update()) { doneLoading(); } else { return; } } float delta = Gdx.graphics.getDeltaTime(); t += delta; Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); isoCam.cam().update(); modelBatch.begin(isoCam.cam()); level.render(modelBatch, environment); unit.render(modelBatch, environment); unit2.render(modelBatch, environment); modelBatch.end(); //fpsLogger.log(); unit.update(delta); unit2.update(delta); player.update(delta); isoCam.update(delta); } @Override public void resize(int width, int height) { isoCam.resizeViewport(); } @Override public void pause() { } @Override public void resume() { } } <file_sep>/drone1/src/com/skorulis/drone1/unit/DroneTurret.java package com.skorulis.drone1.unit; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.skorulis.drone1.def.TurretDef; import com.skorulis.drone1.def.TurretPointDef; import com.skorulis.drone1.scene.SceneNode; public class DroneTurret implements SceneNode { private DroneUnit parent; public Matrix4 relTransform; public ModelInstance modelInstance; private TurretPointDef pointDef; private TurretDef def; private float scale; private Vector3 offset; public DroneTurret(DroneUnit unit, TurretPointDef pointDef, TurretDef def) { this.parent = unit; this.pointDef = pointDef; this.def = def; this.relTransform = new Matrix4(); } public void setup(AssetManager assets) { Model model = assets.get(def.modelName); def.modelLoaded(model); modelInstance = new ModelInstance(model); offset = pointDef.getTurretPos(parent.hullBounds); scale = pointDef.getScale(def.modelBounding); } public void update(float delta) { if(parent.target != null) { relTransform.setToTranslation(offset); relTransform.scl(scale); Vector3 loc = absTransform().getTranslation(new Vector3()); Vector3 tLoc = parent.target.absTransform().getTranslation(new Vector3()); Vector3 dir = tLoc.sub(loc).nor(); dir.y = 0; float angle = def.forward.dot(dir); angle = (float)Math.acos(angle); Vector3 cross = def.forward.cpy().crs(dir); relTransform.rotate(cross, (float)(angle * 180.0 / Math.PI)); } } public void render(ModelBatch batch, Environment environment) { modelInstance.transform = parent.absTransform().cpy().mul(relTransform); batch.render(modelInstance, environment); } public Matrix4 absTransform() { return modelInstance.transform; } public Matrix4 relTransform() { return relTransform; } }
a38ddfffaf29451a3809125352e9ccf14527d125
[ "Markdown", "Java" ]
7
Java
skorulis/drone1-gdx
9f2cd49ec417e9cc3ec7114c4495cbf827384194
5913072f136adf8c3f2a12206352e2e282e883f9
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define casa 20 int gg; int main(int argc, char *argv[]){ gg=15; long int a = 0,b,c=10; float h,g=1.1; long int hh; int q[3] = {1,2,3}; int qqq[] = {1,gg,3}; char t = 'F'; char w = 65; char x = 'a'; long double aa; short int qq; int rt = 1000; int yy = rt + gg; int wdadghsh = 3 +4 ; char bb = t +x ; char tt = 56 +45 ; int k[gg]; int kk[34]; char j[] = {'a','b'}; char jj[] = {12}; char jjj[2] = {'s',27}; tt = 23 + 14 * 2 / 3 - 1; tt = q[0] + 1; q[0] = 3; int ash = 0; q[ash] = 56; int jhg = 2 +3; int *ll; int **lll; int** llll; 3+3; 4+q[0] +15; rt | yy; ash << 3; if(ash << 3){} if(ash << 3); else {} yy++; ++yy; int n=20; do{ n--; }while(n > 1); while(n){ int x=0; if(x==0){ x++; } } while(n); for(;;){} for(;;); for (int xx =0; xx <10; xx++){ yy++; } int xx; for(xx=100; xx>10; xx--){ yy++; } return 0; } <file_sep>bison -d sintax.y flex lexico.l gcc lex.yy.c sintax.tab.c -o analizador -lfl
f5430d6d6249d2a44f1c3118d4ebee016634fca2
[ "C", "Shell" ]
2
C
dvarasm/Analizador-Lexico-Sintaxtico-C
69990c7ba4bbefc049026f5146bcac18c3a898fe
3ae89d6ae170aa2aba194803ed50bc28f528c4ed
refs/heads/master
<file_sep>$(document).ready(function() { $("#calculateBtn").click(function() { // Remove validation and results reset(); let weight = $("input[name=weight]").val(); let height = $("input[name=height").val(); // Validation let noWeight = (weight === ""); let noHeight = (height === ""); if (noWeight || noHeight) { if (noWeight) { $("#weightErrorMessage").html("You must enter a number for the weight"); } if (noHeight) { $("#heightErrorMessage").html("You must enter a number for the height"); } return; } // Calculate BMI let bmi = weight/Math.pow(height, 2); let bodyType = ""; let imgSrc = ""; if (bmi <= 18.5) { bodyType = "Under weight"; imgSrc = "./assets/underweight.png"; } else if (bmi <= 24.9) { bodyType = "Normal weight"; imgSrc = "./assets/normal.png"; } else if (bmi <= 29.9) { bodyType = "Overweight"; imgSrc = "./assets/overweight.png"; } else { bodyType = "Obese"; imgSrc = "./assets/obese.png"; } // Output let name = $("input[name=name]").val(); let output = `<h2>Your Results</h2>`; output += `<b>Name</b> ${name} <br/>`; output += `<b>Results</b> <br/> BMI: ${bmi} <br/> Body Type: ${bodyType} <br/>`; output += `<img src=\"${imgSrc}\"/>`; $("#results").html(output); }); $("#resetBtn").click(function() { reset(); }); }); function reset() { $("#results").html(""); $("#weightErrorMessage").html(""); $("#heightErrorMessage").html(""); }
98f89bcfeb6b8a5bc5ab8ac9550677782f9e852b
[ "JavaScript" ]
1
JavaScript
tiffanyolw/BMICalculator
2aad136d6207fc8263cdba134e25a11f3909ecec
acdf0569e32d1ec4ccc797f52d06692d2a86b90d
refs/heads/master
<repo_name>kaqc/portal<file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/jedis/JedisPublisher.java package me.joeleoli.portal.shared.jedis; import com.google.gson.JsonObject; import lombok.RequiredArgsConstructor; import redis.clients.jedis.Jedis; import java.util.LinkedList; import java.util.Queue; @RequiredArgsConstructor public class JedisPublisher extends Thread { private final JedisSettings jedisSettings; private Queue<JedisQueue> queue = new LinkedList<>(); @Override public void run() { while (true) { if (!this.queue.isEmpty()) { Jedis jedis = null; try { jedis = this.jedisSettings.getJedisPool().getResource(); if (this.jedisSettings.hasPassword()) { jedis.auth(this.jedisSettings.getPassword()); } while (!this.queue.isEmpty()) { JedisQueue queue = this.queue.poll(); JsonObject json = new JsonObject(); json.addProperty("action", queue.getAction().name()); json.add("data", queue.getData()); jedis.publish(queue.getChannel(), json.toString()); } } finally { if (jedis != null) { jedis.close(); } } } try { Thread.sleep(50L); } catch (InterruptedException e) { e.printStackTrace(); } } } public void write(String channel, JedisAction action, JsonObject data) { this.queue.add(new JedisQueue(channel, action, data)); } } <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/command/commands/LeaveQueueCommand.java package me.joeleoli.portal.bukkit.command.commands; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.bukkit.command.BaseCommand; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.jedis.JedisChannel; import me.joeleoli.portal.shared.queue.Queue; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class LeaveQueueCommand extends BaseCommand { public LeaveQueueCommand() { super("leavequeue"); } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (!(commandSender instanceof Player)) { commandSender.sendMessage(CONSOLE_SENDER); return true; } Player player = (Player) commandSender; Queue queue = Queue.getByPlayer(player.getUniqueId()); if (queue == null) { player.sendMessage(ChatColor.RED + "You are not in a queue."); return true; } JsonObject data = new JsonObject(); data.addProperty("uuid", player.getUniqueId().toString()); Portal.getInstance().getPublisher().write(JedisChannel.INDEPENDENT, JedisAction.REMOVE_PLAYER, data); return true; } } <file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/jedis/JedisSettings.java package me.joeleoli.portal.shared.jedis; import lombok.Getter; import redis.clients.jedis.JedisPool; @Getter public class JedisSettings { private final String address; private final int port; private final String password; private final JedisPool jedisPool; public JedisSettings(String address, int port, String password) { this.address = address; this.port = port; this.password = <PASSWORD>; this.jedisPool = new JedisPool(this.address, this.port); } public boolean hasPassword() { return this.password != null && !this.password.equals(""); } } <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/listener/PlayerListener.java package me.joeleoli.portal.bukkit.listener; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.jedis.JedisChannel; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; public class PlayerListener implements Listener { @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { JsonObject data = new JsonObject(); data.addProperty("uuid", event.getPlayer().getUniqueId().toString()); Portal.getInstance().getPublisher().write(JedisChannel.INDEPENDENT, JedisAction.REMOVE_PLAYER, data); } } <file_sep>/Independent/config.properties hubs=hub-01,hub-02 queues=test1,test2,test3 redis-host=127.0.0.1 redis-port=6379 redis-password=dev <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/thread/UpdateThread.java package me.joeleoli.portal.bukkit.thread; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.jedis.JedisChannel; public class UpdateThread extends Thread { @Override public void run() { while (true) { Portal.getInstance().getPublisher().write(JedisChannel.INDEPENDENT, JedisAction.UPDATE, Portal.getInstance().getPortalServer().getServerData()); Portal.getInstance().getPublisher().write(JedisChannel.BUKKIT, JedisAction.UPDATE, Portal.getInstance().getPortalServer().getServerData()); try { Thread.sleep(2500L); } catch (InterruptedException e) { e.printStackTrace(); } } } } <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/Portal.java package me.joeleoli.portal.bukkit; import me.joeleoli.portal.bukkit.command.commands.*; import me.joeleoli.portal.bukkit.config.FileConfig; import me.joeleoli.portal.bukkit.config.Language; import me.joeleoli.portal.bukkit.jedis.PortalSubscriptionHandler; import me.joeleoli.portal.bukkit.listener.PlayerListener; import me.joeleoli.portal.bukkit.priority.PriorityProvider; import me.joeleoli.portal.bukkit.priority.impl.DefaultPriorityProvider; import me.joeleoli.portal.bukkit.server.Server; import me.joeleoli.portal.bukkit.thread.ReminderThread; import me.joeleoli.portal.bukkit.thread.UpdateThread; import me.joeleoli.portal.shared.jedis.JedisChannel; import me.joeleoli.portal.shared.jedis.JedisPublisher; import me.joeleoli.portal.shared.jedis.JedisSettings; import me.joeleoli.portal.shared.jedis.JedisSubscriber; import lombok.Getter; import lombok.Setter; import org.bukkit.plugin.java.JavaPlugin; @Getter public class Portal extends JavaPlugin { @Getter private static Portal instance; private FileConfig mainConfig; private Language language; private JedisSettings settings; private JedisPublisher publisher; private JedisSubscriber subscriber; private Server portalServer; @Setter private PriorityProvider priorityProvider; @Override public void onEnable() { instance = this; this.mainConfig = new FileConfig(this, "config.yml"); this.language = new Language(); this.language.load(); this.portalServer = new Server( this.mainConfig.getConfig().getString("server.id"), this.mainConfig.getConfig().getBoolean("server.hub") ); this.settings = new JedisSettings( this.mainConfig.getConfig().getString("redis.host"), this.mainConfig.getConfig().getInt("redis.port"), !this.mainConfig.getConfig().contains("redis.password") ? null : this.mainConfig.getConfig().getString("redis.password") ); this.subscriber = new JedisSubscriber(JedisChannel.BUKKIT, this.settings, new PortalSubscriptionHandler()); this.publisher = new JedisPublisher(this.settings); this.publisher.start(); this.priorityProvider = new DefaultPriorityProvider(); // Start threads new UpdateThread().start(); new ReminderThread().start(); // Register commands new JoinQueueCommand(); new LeaveQueueCommand(); new ForceSendCommand(); new DataDumpCommand(); new QueueToggleCommand(); new QueueClearCommand(); // Register listeners this.getServer().getPluginManager().registerEvents(new PlayerListener(), this); // Register plugin message channels this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); } @Override public void onDisable() { if (this.settings.getJedisPool() != null && !this.settings.getJedisPool().isClosed()) { this.settings.getJedisPool().close(); } } } <file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/queue/QueueRank.java package me.joeleoli.portal.shared.queue; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class QueueRank implements Comparable { private String name; private int priority; @Override public int compareTo(Object o) { int result = 0; if (o instanceof QueueRank) { result = this.priority - ((QueueRank) o).priority; } return result; } } <file_sep>/README.md # Portal A multi-proxy player queue. ## How It Works * Player joins a queue through a hub. * Hub sends a message to the Independent module to add that player to that queue. * Independent module constantly checks if a queue can send a player. If a player can be sent, a message is broadcasted to all Bukkit instances that the next player in the queue (based on rank priority) should be sent to the server. * Any Bukkit instance that contains the player will use plugin messages to send the player. ## Commands | Command syntax | Description | Permission | | ---------------------------- | ----------------------------------- | ---------------- | | /queueclear \<queue\> | Clear the list of a queue | portal.clear | | /queuetoggle \<queue\> | Toggle (pause) a queue | portal.toggle | | /forcesend \<player\> \<server\> | Force sends a player to a server | portal.forcesend | | /datadump | Displays all server data and queues | portal.datadump | ## Priority Queue priority can be assigned through permissions (config.yml) or by using your own implementation. To implement your own priority system, extend `PriorityProvider` and set the instance provider using `Portal.getInstance().setPriorityProvider(provider)`. ## Bypass Players that have the `portal.bypass` permission will immediately be sent to a server instead of joining a queue.<file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/jedis/PortalSubscriptionHandler.java package me.joeleoli.portal.bukkit.jedis; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.bukkit.util.BungeeUtil; import me.joeleoli.portal.shared.jedis.JedisSubscriptionHandler; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.queue.Queue; import me.joeleoli.portal.shared.queue.QueuePlayer; import me.joeleoli.portal.shared.queue.QueuePlayerComparator; import me.joeleoli.portal.shared.queue.QueueRank; import me.joeleoli.portal.shared.server.ServerData; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.util.PriorityQueue; import java.util.UUID; public class PortalSubscriptionHandler implements JedisSubscriptionHandler { @Override public void handleMessage(JsonObject json) { JedisAction action = JedisAction.valueOf(json.get("action").getAsString()); JsonObject data = json.get("data").isJsonNull() ? null : json.get("data").getAsJsonObject(); if (data == null) { return; } switch (action) { case UPDATE: { final String name = data.get("name").getAsString(); if (!Portal.getInstance().getPortalServer().isHub()) { return; } ServerData serverData = ServerData.getByName(name); if (serverData == null) { serverData = new ServerData(name); } serverData.setOnlinePlayers(data.get("online-players").getAsInt()); serverData.setMaximumPlayers(data.get("maximum-players").getAsInt()); serverData.setWhitelisted(data.get("whitelisted").getAsBoolean()); serverData.setLastUpdate(System.currentTimeMillis()); } break; case LIST: { if (!Portal.getInstance().getPortalServer().isHub()) { return; } for (JsonElement e : data.get("queues").getAsJsonArray()) { final JsonObject queueJson = e.getAsJsonObject(); final String name = queueJson.get("name").getAsString(); Queue queue = Queue.getByName(name); if (queue == null) { queue = new Queue(name); } PriorityQueue<QueuePlayer> players = new PriorityQueue<>(new QueuePlayerComparator()); for (JsonElement pe : queueJson.get("players").getAsJsonArray()) { JsonObject player = pe.getAsJsonObject(); JsonObject rank = player.get("rank").getAsJsonObject(); QueueRank queueRank = new QueueRank(); queueRank.setName(rank.get("name").getAsString()); queueRank.setPriority(rank.get("priority").getAsInt()); QueuePlayer queuePlayer = new QueuePlayer(); queuePlayer.setUuid(UUID.fromString(player.get("uuid").getAsString())); queuePlayer.setRank(queueRank); queuePlayer.setInserted(player.get("inserted").getAsLong()); players.add(queuePlayer); } queue.setPlayers(players); queue.setEnabled(queueJson.get("status").getAsBoolean()); } } break; case ADDED_PLAYER: { Queue queue = Queue.getByName(data.get("queue").getAsString()); if (queue == null) { return; } JsonObject player = data.get("player").getAsJsonObject(); JsonObject rank = player.get("rank").getAsJsonObject(); QueueRank queueRank = new QueueRank(); queueRank.setName(rank.get("name").getAsString()); queueRank.setPriority(rank.get("priority").getAsInt()); QueuePlayer queuePlayer = new QueuePlayer(); queuePlayer.setUuid(UUID.fromString(player.get("uuid").getAsString())); queuePlayer.setRank(queueRank); queuePlayer.setInserted(player.get("inserted").getAsLong()); queue.getPlayers().add(queuePlayer); Player bukkitPlayer = Portal.getInstance().getServer().getPlayer(queuePlayer.getUuid()); if (bukkitPlayer != null) { for (String message : Portal.getInstance().getLanguage().getAdded(bukkitPlayer, queue)) { bukkitPlayer.sendMessage(message); } } } break; case REMOVED_PLAYER: { Queue queue = Queue.getByName(data.get("queue").getAsString()); if (queue == null) { return; } UUID uuid = UUID.fromString(data.get("player").getAsJsonObject().get("uuid").getAsString()); queue.getPlayers().removeIf(queuePlayer -> queuePlayer.getUuid().equals(uuid)); Player bukkitPlayer = Portal.getInstance().getServer().getPlayer(uuid); if (bukkitPlayer != null) { for (String message : Portal.getInstance().getLanguage().getRemoved(queue)) { bukkitPlayer.sendMessage(message); } } } break; case SEND_PLAYER_SERVER: { String server = data.get("server").getAsString(); Player player; // Send player by username or uuid if (data.has("username")) { player = Portal.getInstance().getServer().getPlayer(data.get("username").getAsString()); } else { player = Portal.getInstance().getServer().getPlayer(UUID.fromString(data.get("uuid").getAsString())); } if (player == null) { return; } player.sendMessage(ChatColor.GREEN + "Sending you to " + server); BungeeUtil.sendToServer(player, server); } break; case MESSAGE_PLAYER: { Player player = Portal.getInstance().getServer().getPlayer(data.get("uuid").getAsString()); if (player == null) { return; } player.sendMessage(ChatColor.translateAlternateColorCodes('&', data.get("message").getAsString())); } break; } } } <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/command/BaseCommand.java package me.joeleoli.portal.bukkit.command; import me.joeleoli.portal.bukkit.Portal; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public abstract class BaseCommand implements CommandExecutor { protected static final String NO_PERMISSION = ChatColor.RED + "No permission."; protected static final String CONSOLE_SENDER = ChatColor.RED + "This command can only be peformed in-game."; public BaseCommand(String name) { Portal.getInstance().getCommand(name).setExecutor(this); } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { commandSender.sendMessage("Command not handled"); return true; } }<file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/command/commands/QueueClearCommand.java package me.joeleoli.portal.bukkit.command.commands; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.bukkit.command.BaseCommand; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.jedis.JedisChannel; import me.joeleoli.portal.shared.queue.Queue; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class QueueClearCommand extends BaseCommand { public QueueClearCommand() { super("queueclear"); } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if (!commandSender.hasPermission("portal.clear") && !commandSender.isOp()) { commandSender.sendMessage(NO_PERMISSION); return true; } if (args.length == 0) { commandSender.sendMessage(ChatColor.RED + "Usage: /queueclear <server>"); return true; } Queue queue = Queue.getByName(args[0]); if (queue == null) { commandSender.sendMessage(ChatColor.RED + "That queue does not exist."); return true; } queue.getPlayers().clear(); JsonObject json = new JsonObject(); json.addProperty("queue", queue.getName()); Portal.getInstance().getPublisher().write(JedisChannel.INDEPENDENT, JedisAction.CLEAR_PLAYERS, json); commandSender.sendMessage(ChatColor.GREEN + "Cleared list of " + queue.getName()); return true; } } <file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/queue/QueuePlayerComparator.java package me.joeleoli.portal.shared.queue; import java.util.Comparator; public class QueuePlayerComparator implements Comparator<QueuePlayer> { @Override public int compare(QueuePlayer firstPlayer, QueuePlayer secondPlayer) { return firstPlayer.compareTo(secondPlayer); } }<file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/command/commands/QueueToggleCommand.java package me.joeleoli.portal.bukkit.command.commands; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import me.joeleoli.portal.bukkit.command.BaseCommand; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.jedis.JedisChannel; import me.joeleoli.portal.shared.queue.Queue; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class QueueToggleCommand extends BaseCommand { public QueueToggleCommand() { super("queuetoggle"); } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if (!commandSender.hasPermission("portal.toggle") && !commandSender.isOp()) { commandSender.sendMessage(NO_PERMISSION); return true; } if (args.length == 0) { commandSender.sendMessage(ChatColor.RED + "Usage: /queuetoggle <server>"); return true; } Queue queue = Queue.getByName(args[0]); if (queue == null) { commandSender.sendMessage(ChatColor.RED + "That queue does not exist."); return true; } queue.setEnabled(!queue.isEnabled()); JsonObject json = new JsonObject(); json.addProperty("queue", queue.getName()); Portal.getInstance().getPublisher().write(JedisChannel.INDEPENDENT, JedisAction.TOGGLE, json); commandSender.sendMessage(ChatColor.GREEN + "Changed status of `" + queue.getName() + "` to " + queue.isEnabled()); return true; } } <file_sep>/Bukkit/src/main/java/me/joeleoli/portal/bukkit/server/Server.java package me.joeleoli.portal.bukkit.server; import com.google.gson.JsonObject; import me.joeleoli.portal.bukkit.Portal; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class Server { private String name; private boolean hub; public JsonObject getServerData() { JsonObject object = new JsonObject(); object.addProperty("name", this.name); object.addProperty("online-players", Portal.getInstance().getServer().getOnlinePlayers().size()); object.addProperty("maximum-players", Portal.getInstance().getServer().getMaxPlayers()); object.addProperty("whitelisted", Portal.getInstance().getServer().hasWhitelist()); return object; } } <file_sep>/Independent/src/main/java/me/joeleoli/portal/independent/thread/QueueThread.java package me.joeleoli.portal.independent.thread; import com.google.gson.JsonObject; import me.joeleoli.portal.independent.Portal; import me.joeleoli.portal.shared.jedis.JedisChannel; import me.joeleoli.portal.shared.queue.Queue; import me.joeleoli.portal.shared.queue.QueuePlayer; import me.joeleoli.portal.shared.jedis.JedisAction; import me.joeleoli.portal.shared.server.ServerData; public class QueueThread extends Thread { private static final Long SEND_DELAY = 500L; @Override public void run() { while (true) { for (Queue queue : Queue.getQueues()) { ServerData serverData = queue.getServerData(); if (serverData == null) { continue; } if (!queue.isEnabled()) { continue; } if (!serverData.isOnline()) { continue; } if (serverData.isWhitelisted()) { continue; } if (serverData.getOnlinePlayers() >= serverData.getMaximumPlayers()) { continue; } QueuePlayer next = queue.getPlayers().poll(); if (next != null) { JsonObject data = new JsonObject(); data.addProperty("server", queue.getName()); data.addProperty("uuid", next.getUuid().toString()); Portal.getInstance().getPublisher().write(JedisChannel.BUKKIT, JedisAction.SEND_PLAYER_SERVER, data); } } try { Thread.sleep(SEND_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } } } } <file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/jedis/JedisAction.java package me.joeleoli.portal.shared.jedis; public enum JedisAction { LIST, UPDATE, TOGGLE, CLEAR_PLAYERS, ADD_PLAYER, ADDED_PLAYER, REMOVE_PLAYER, REMOVED_PLAYER, SEND_PLAYER_SERVER, SEND_PLAYER_HUB, MESSAGE_PLAYER } <file_sep>/Shared/src/main/java/me/joeleoli/portal/shared/queue/Queue.java package me.joeleoli.portal.shared.queue; import me.joeleoli.portal.shared.server.ServerData; import lombok.Getter; import lombok.Setter; import java.util.*; @Getter public class Queue { @Getter private static List<Queue> queues = new ArrayList<>(); private String name; @Setter private PriorityQueue<QueuePlayer> players = new PriorityQueue<>(new QueuePlayerComparator()); @Setter private boolean enabled; public Queue(String name) { this.name = name; queues.add(this); } public ServerData getServerData() { return ServerData.getByName(this.name); } public boolean containsPlayer(UUID uuid) { for (QueuePlayer player : this.players) { if (player.getUuid().equals(uuid)) { return true; } } return false; } public int getPosition(UUID uuid) { if (!this.containsPlayer(uuid)) { return 0; } PriorityQueue<QueuePlayer> queue = new PriorityQueue<>(this.players); int position = 0; while (!queue.isEmpty()) { QueuePlayer player = queue.poll(); if (player.getUuid().equals(uuid)) { break; } position++; } return position + 1; } @Override public String toString() { return ""; } public static Queue getByName(String name) { for (Queue queue : Queue.getQueues()) { if (queue.getName().equalsIgnoreCase(name)) { return queue; } } return null; } public static Queue getByPlayer(UUID uuid) { for (Queue queue : Queue.getQueues()) { for (QueuePlayer queuePlayer : queue.getPlayers()) { if (queuePlayer.getUuid().equals(uuid)) { return queue; } } } return null; } }
e81db550181b857eb657cf7d2027c9cc4ee5dd70
[ "Markdown", "Java", "INI" ]
18
Java
kaqc/portal
91f25612a724c0fc7bf9f6f36f537a3c0c451331
d2a853fdb2a2fd34929bc4df910736d9f29dd13f
refs/heads/master
<file_sep>/** * set up requirejs config * @function * @return {object} configuration option */ ( function( ) { var options = { baseUrl: "/public/script" , paths : { // lib "requireLib" : "lib/requirejs/require" , "async" : "lib/requirejs/plugin/async" , "text" : "lib/requirejs/plugin/text" , "i18n" : "lib/requirejs/plugin/i18n" , "domReady" : "lib/requirejs/plugin/domReady" , "jquery" : "lib/jquery/jquery" , "_" : "lib/underscore/underscore" , "backbone" : "lib/backbone/backbone" // modules , "main" : "modules/main" , "todo" : "modules/todo" } , shim: { "_" : { "exports" : "_" } , "backbone" : { "exports" : "Backbone" , "deps" : [ "jquery", "_" ] } } //, urlArgs : "bust=" + ( new Date() ).getTime() }; // step: configure requirejs with the application's configuration option requirejs.config( options ); return options; } )( ); <file_sep>/** * @module todo * @moduleType require * @deps jquery, _, backbone * */ requirejs( [ "jquery", "_", "backbone" ], function( $, _, Backbone ) { "use strict"; /** * todo model blueprint * @class Todo */ var Todo = Backbone.Model.extend( { defaults: { title: "" , completed: false } , validate: function( attr ) { if( attr && attr.completed ) { if( attr.completed !== true || attr.completed !== false ) { return "completed must only take a boolean value" } } } , getTitle: function( ) { return this.get( "title" ); } , setTitle: function( val ) { return this.set( { "title": val } ); } , unsetAll: function( ) { this.clear( ); } , getAll: function( ) { return this.toJSON( ); } } ); // Todo model instance var myTodo = new Todo( { title: "Check attributes property of the logged models in the console." } ); console.log( myTodo.getTitle( ) ) ; /** * todo view * @class TodoView */ var TodoView = Backbone.View.extend( { tagName: "li" , tmpl: _.template( $("#item-template").html( ) ) , events: { "dblclick label": "edit" , "keypress .edit": "updateOnEnter" , "blur .edit": "close" } , initialize: function( ) { this.$el = $("#todo") } , render: function( ) { this.$el.html( this.tmpl( this.model.toJSON( ) ) ); this.input = this.$( ".edit" ); return this; } , edit: function( ) { // executed when todo label is double clicked } , close: function( ) { // executed when todo loses focus } , updateOnEnter: function( ) { // executed on each keypress when in todo edit mode, // but we wait for enter to get in action } } ); // Todo view instance var todoView = new TodoView( { model: myTodo } ); /** * todo collection * @class TodosCollection */ var TodosCollection = Backbone.Collection.extend( { model: Todo } ); var todos = new TodosCollection( myTodo ); } );
ddef2191fe564f191fdb567b1c628790b7a46231
[ "JavaScript" ]
2
JavaScript
html5webster/learning-backbone
35438e4139a2ea154f3b64ca968dd6abca4f173f
2f5a9ef0a854f8ec55e68942bdfa6b36dd66fb08
refs/heads/main
<repo_name>akashlhire/Python-based-Student-Management-System<file_sep>/requirements.txt tkinter matplotlib pandas numpy cx_Oracle csv bs4 requests socket Pillow <file_sep>/StudentDataManagementSystem.py from tkinter import * from tkinter import messagebox from tkinter import scrolledtext import matplotlib.pyplot as plt import pandas as pd import numpy as np import cx_Oracle import tkinter as tk import os import csv import bs4 import requests import socket from PIL import Image, ImageTk try: socket.create_connection(("www.google.com",80)) res=requests.get("https://ipinfo.io/") data=res.json() city=data['city'] a3="http://api.openweathermap.org/data/2.5/weather?units=metric" a4="&q="+city a5="&appid=9922a2afc7ccc710352870947a3eb7d1" apia=a3+a4+a5 res1=requests.get(apia) wdata=requests.get(apia).json() main=wdata['main'] temp=main['temp'] except OSError: print("check network") a1="https://www.brainyquote.com" res=requests.get("https://www.brainyquote.com/quote_of_the_day") soup=bs4.BeautifulSoup(res.text,'lxml') quote=soup.find('img',{"class":"p-qotd"}) a2=quote['data-img-url'] img=a1+a2 r=requests.get(img) with open("image.gif","wb")as f: f.write(r.content) class DemoSplashScreen: def __init__(self, parent): self.parent = parent self.aturSplash() self.aturWindow() def aturSplash(self): self.gambar = Image.open('image.gif') self.imgSplash = ImageTk.PhotoImage(self.gambar) def aturWindow(self): lebar, tinggi = self.gambar.size setengahLebar = (self.parent.winfo_screenwidth()-lebar)//2 setengahTinggi = (self.parent.winfo_screenheight()-tinggi)//2 self.parent.geometry("%ix%i+%i+%i" %(lebar, tinggi, setengahLebar,setengahTinggi)) Label(self.parent, image=self.imgSplash).pack() if __name__ == '__main__': root = Tk() root.overrideredirect(True) c = Label(root, text=city) c.pack(pady=10) t = Label(root, text=temp) t.pack(padx=10) app = DemoSplashScreen(root) root.after(6010, root.destroy) root.mainloop() root=Tk() root.title("<NAME>. ") root.geometry("400x400+200+200") def f1(): adSt.deiconify() root.withdraw() def f3(): viSt.deiconify() root.withdraw() con=None cursor=None try: con=cx_Oracle.connect("system/abc123") cursor=con.cursor() sql="select * from student1 " cursor.execute(sql) data=cursor.fetchall() msg='' for d in data: msg = "rno " + str(d[0]) + " name "+ str(d[1])+" marks " + str(d[2]) +"\n" stData.insert(INSERT,msg) except cx_Oracle.DatabaseError as e: con.rollback() print("insert issue ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() def f6(): upSt.deiconify() root.withdraw() def f8(): deSt.deiconify() root.withdraw() def f13(): con=None cursor=None try: SQL="SELECT * FROM student1" # Network drive somewhere filename="Output.csv" FILE=open(filename,"w"); output=csv.writer(FILE) con=cx_Oracle.connect("system/abc123") cursor=con.cursor() cursor.execute(SQL) for row in cursor: output.writerow(row) cursor.close() con.close() FILE.close() x=[] y=[] df=pd.read_csv("Output.csv",header=None) x=df[1] y=df[2] plt.bar(x,y,width=2.0) plt.title('Performance') plt.xlabel('ROLL NO') plt.ylabel('MARKS') plt.show() except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) btnAdd=Button(root,text="Add",font=("arial",16,'bold'),width=10,command=f1) btnView=Button(root,text="View",font=("arial",16,'bold'),width=10,command=f3) btnUpdate=Button(root,text="Update",font=("arial",16,'bold'),width=10,command=f6) btnDelete=Button(root,text="Delete",font=("arial",16,'bold'),width=10,command=f8) btnGraph=Button(root,text="Graph",font=("arial",16,'bold'),width=10,command=f13) btnAdd.pack(pady=10) btnView.pack(pady=10) btnUpdate.pack(pady=10) btnDelete.pack(pady=10) btnGraph.pack(pady=10) adSt=Toplevel(root) adSt.title("Add Student") adSt.geometry("400x400+200+200") adSt.withdraw() def f2(): root.deiconify() adSt.withdraw() def f5(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entAddRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entAddRno.focus() return ename=entAddName.get() if ename.isalpha(): name=ename else: messagebox.showerror("Error", "Please enter a valid name(string)") entAddName.focus() return emarks=entAddMarks.get() if emarks.isdigit() and int(emarks)>=0 and int(emarks)<101: marks=int(emarks) else: messagebox.showerror("Error", "Enter marks within limit of 0 to 100") entAddMarks.focus() return cursor=con.cursor() sql="insert into student1 values('%d','%s','%d')" args=(rno,name,marks) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows inserted " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() lblAddRno=Label(adSt,text="enter rno ") lblAddName=Label(adSt,text="enter Name ") lblAddMarks=Label(adSt,text="enter Marks ") entAddRno=Entry(adSt,bd=5) entAddName=Entry(adSt,bd=5) entAddMarks=Entry(adSt,bd=5) btnAddSave=Button(adSt,text="Save",command=f5) btnAddBack=Button(adSt,text="Back",command=f2) lblAddRno.pack(pady=10) entAddRno.pack(pady=10) lblAddName.pack(pady=10) entAddName.pack(pady=10) lblAddMarks.pack(pady=10) entAddMarks.pack(pady=10) btnAddSave.pack(pady=10) btnAddBack.pack(pady=10) def f4(): root.deiconify() viSt.withdraw() viSt=Toplevel(root) viSt.title("View Student") viSt.geometry("400x400+200+200") viSt.withdraw() stData=scrolledtext.ScrolledText(viSt,width=30,height=5) btnViewBack=Button(viSt,text="Back",command=f4) stData.pack(pady=10) btnViewBack.pack(pady=10) def f7(): root.deiconify() upSt.withdraw() def f10(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entUpRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entUpRno.focus() return ename=entUpName.get() if ename.isalpha(): name=ename else: messagebox.showerror("Error", "Please enter a valid name(string)") entUpName.focus() return cursor=con.cursor() sql="update student1 set name = '%s' where rno = '%d'" args=(name,rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows updated " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() def f11(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entUpRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entUpRno.focus() return emarks=entUpMarks.get() if emarks.isdigit() and int(emarks)>=0 and int(emarks)<101: marks=int(emarks) else: messagebox.showerror("Error", "Please enter marks within limit of 0 to 100") entUpMarks.focus() return cursor=con.cursor() sql="update student1 set marks = '%d' where rno = '%d'" args=(marks,rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows updated " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() upSt=Toplevel(root) upSt.title("Update Student") upSt.geometry("400x400+200+200") upSt.withdraw() lblUpRno=Label(upSt,text="Enter rno ") lblUpName=Label(upSt,text="Update Name ") lblUpMarks=Label(upSt,text="Update Marks ") entUpRno=Entry(upSt,bd=5) entUpName=Entry(upSt,bd=5) entUpMarks=Entry(upSt,bd=5) btnUpName=Button(upSt,text="Update Name",command=f10) btnUpMarks=Button(upSt,text="Update Marks",command=f11) btnUpBack=Button(upSt,text="Back",command=f7) lblUpRno.pack(pady=10) entUpRno.pack(pady=10) lblUpName.pack(pady=10) entUpName.pack(pady=10) lblUpMarks.pack(pady=10) entUpMarks.pack(pady=10) btnUpName.pack(pady=10) btnUpMarks.pack(padx=10) btnUpBack.pack(pady=10) def f9(): root.deiconify() deSt.withdraw() def f12(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entDeRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entDeRno.focus() return cursor=con.cursor() sql="delete from student1 where rno ='%d'" args=(rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows deleted " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() deSt=Toplevel(root) deSt.title("Delete Student") deSt.geometry("400x400+200+200") deSt.withdraw() lblDeRno=Label(deSt,text="Enter rno ") entDeRno=Entry(deSt,bd=5) btnDeSave=Button(deSt,text="Delete",command=f12) btnDeBack=Button(deSt,text="Back",command=f9) lblDeRno.pack(pady=10) entDeRno.pack(pady=10) btnDeSave.pack(pady=10) btnDeBack.pack(pady=10) root.mainloop() <file_sep>/proj.py from tkinter import* from tkinter import messagebox from tkinter import scrolledtext import cx_Oracle root=Tk() root.title("<NAME>.") #S.M.S.--->student management system root.geometry("400x400+200+200") def f1(): adSt.deiconify() root.withdraw() def f3(): viSt.deiconify() root.withdraw() con=None cursor=None try: con=cx_Oracle.connect("system/abc123") cursor=con.cursor() sql="select * from student" cursor.execute(sql) data=cursor.fetchall() msg='' for d in data: msg=msg + "rno" + str(d[0]) + "name" + str(d[1]) + "marks" + str(d[2]) + "\n" stData.insert(INSERT,msg) except cx_Oracle.DatabaseError as e: print("select issue",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() btnAdd=Button(root, text="Add", font=("arial", 16, 'bold'),width=10, command=f1) btnView=Button(root, text="View", font=("arial", 16, 'bold'),width=10, command=f3) btnUpdate=Button(root, text="Update", font=("arial", 16, 'bold'),width=10) btnDelete=Button(root, text="Delete", font=("arial", 16, 'bold'),width=10) btnGraph=Button(root, text="Graph", font=("arial", 16, 'bold'),width=10) btnAdd.pack(pady=10) btnView.pack(pady=10) btnUpdate.pack(pady=10) btnDelete.pack(pady=10) btnGraph.pack(pady=10) adSt=Toplevel(root) adSt.title("Add Student") adSt.geometry("400x400+200+200") adSt.withdraw() def f2(): root.deiconify() adSt.withdraw() def f5(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=int(entAddRno.get()) name=entAddName.get() marks=int(entAddMarks.get()) cursor=con.cursor() sql="insert into student values('%d', '%s', '%d')" args=(rno,name,marks) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) + "rows inserted" messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() messagebox.showerror("Failure",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() lblAddRno = Label(adSt, text="enter rno") lblAddName = Label(adSt, text="enter name") lblAddMarks = Label(adSt, text="enter marks") entAddRno=Entry(adSt, bd=5) entAddName=Entry(adSt, bd=5) entAddMarks=Entry(adSt, bd=5) btnAddSave=Button(adSt, text="Save", command=f5) btnAddBack=Button(adSt, text="Back", command=f2) lblAddRno.pack(pady=10) entAddRno.pack(pady=10) lblAddName.pack(pady=10) entAddName.pack(pady=10) lblAddMarks.pack(pady=10) entAddMarks.pack(pady=10) btnAddSave.pack(pady=10) btnAddBack.pack(pady=10) def f4(): root.deiconify() viSt.withdraw() viSt=Toplevel(root) #Toplevel-->another GUI viSt.title("View Student") viSt.geometry("400x400+200+200") viSt.withdraw() stData=scrolledtext.ScrolledText(viSt, width=30, height=5) btnViewBack=Button(viSt, text="Back", command=f4) stData.pack(pady=10) btnViewBack.pack(pady=10) root.mainloop()<file_sep>/p3.py from bs4 import BeautifulSoup import requests import random popular_choice = ['motivational', 'life', 'positive', 'friendship', 'success', 'happiness', 'love'] def get_quotes(): url = "http://www.brainyquote.com/quote_of_the_day.html" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") quotes = [] for quote in soup.find_all('a', {'title': 'view quote'}): quotes.append(quote.contents[0]) random.shuffle(quotes) result = quotes return result print(get_quotes()) <file_sep>/README.md # Python-based-Student-Management-System # Setup Oracle database server on system # pip install -r requirements.txt # run StudentDataManagementSystem.py <file_sep>/p.py from tkinter import * from tkinter import messagebox from tkinter import scrolledtext import matplotlib.pyplot as plt import pandas as pd import numpy as np import cx_Oracle import tkinter as tk import os import csv import bs4 import requests from PIL import Image, ImageTk #import ttk a1="https://www.brainyquote.com" res=requests.get("https://www.brainyquote.com/quote_of_the_day") soup=bs4.BeautifulSoup(res.text,'lxml') quote=soup.find('img',{"class":"p-qotd"}) print(quote) a2=quote['data-img-url'] img=a1+a2 r=requests.get(img) with open("image.gif","wb")as f: f.write(r.content) root = tk.Tk() # show no frame root.overrideredirect(True) width = root.winfo_screenwidth() height = root.winfo_screenheight() root.geometry('%dx%d+%d+%d' % (width*0.8, height*0.8, width*0.1, height*0.1)) # take a .jpg picture you like, add text with a program like PhotoFiltre # (free from http://www.photofiltre.com) and save as a .gif image file image_file = "image.gif" #assert os.path.exists(image_file) # use Tkinter's PhotoImage for .gif files image = tk.PhotoImage(file=image_file) canvas = tk.Canvas(root, height=height*0.8, width=width*0.8, bg="brown") canvas.create_image(width*0.8/2, height*0.8/2, image=image) canvas.pack() # show the splash screen for 3000 milliseconds then destroy root.after(3000, root.destroy) root.mainloop() root=Tk() root.title("S. M. S. ") root.geometry("400x400+200+200") def f1(): adSt.deiconify() root.withdraw() def f3(): viSt.deiconify() root.withdraw() con=None cursor=None try: con=cx_Oracle.connect("system/abc123") cursor=con.cursor() sql="select * from student1 " cursor.execute(sql) data=cursor.fetchall() msg='' for d in data: msg = "rno " + str(d[0]) + " name "+ str(d[1])+" marks " + str(d[2]) +"\n" stData.insert(INSERT,msg) except cx_Oracle.DatabaseError as e: con.rollback() print("insert issue ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() def f6(): upSt.deiconify() root.withdraw() def f8(): deSt.deiconify() root.withdraw() def f13(): con=None cursor=None try: SQL="SELECT * FROM student1" # Network drive somewhere filename="Output.csv" FILE=open(filename,"w"); output=csv.writer(FILE) con=cx_Oracle.connect("system/abc123") cursor=con.cursor() cursor.execute(SQL) for row in cursor: output.writerow(row) cursor.close() con.close() FILE.close() x=[] y=[] df=pd.read_csv("Output.csv",header=None) x=df[0] y=df[2] plt.bar(x,y,width=2.0) plt.title('Performance') plt.xlabel('ROLL NO') plt.ylabel('MARKS') plt.show() except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) btnAdd=Button(root,text="Add",font=("arial",16,'bold'),width=10,command=f1) btnView=Button(root,text="View",font=("arial",16,'bold'),width=10,command=f3) btnUpdate=Button(root,text="Update",font=("arial",16,'bold'),width=10,command=f6) btnDelete=Button(root,text="Delete",font=("arial",16,'bold'),width=10,command=f8) btnGraph=Button(root,text="Graph",font=("arial",16,'bold'),width=10,command=f13) btnAdd.pack(pady=10) btnView.pack(pady=10) btnUpdate.pack(pady=10) btnDelete.pack(pady=10) btnGraph.pack(pady=10) adSt=Toplevel(root) adSt.title("Add Student") adSt.geometry("400x400+200+200") adSt.withdraw() def f2(): root.deiconify() adSt.withdraw() def f5(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entAddRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entAddRno.focus() return ename=entAddName.get() if ename.isalpha(): name=ename else: messagebox.showerror("Error", "Please enter a valid name(string)") entAddName.focus() return emarks=entAddMarks.get() if emarks.isdigit() and int(emarks)>=0 and int(emarks)<101: marks=int(emarks) else: messagebox.showerror("Error", "Enter marks within limit of 0 to 100") entAddMarks.focus() return cursor=con.cursor() sql="insert into student1 values('%d','%s','%d')" args=(rno,name,marks) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows inserted " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() lblAddRno=Label(adSt,text="enter rno ") lblAddName=Label(adSt,text="enter Name ") lblAddMarks=Label(adSt,text="enter Marks ") entAddRno=Entry(adSt,bd=5) entAddName=Entry(adSt,bd=5) entAddMarks=Entry(adSt,bd=5) btnAddSave=Button(adSt,text="Save",command=f5) btnAddBack=Button(adSt,text="Back",command=f2) lblAddRno.pack(pady=10) entAddRno.pack(pady=10) lblAddName.pack(pady=10) entAddName.pack(pady=10) lblAddMarks.pack(pady=10) entAddMarks.pack(pady=10) btnAddSave.pack(pady=10) btnAddBack.pack(pady=10) def f4(): root.deiconify() viSt.withdraw() viSt=Toplevel(root) viSt.title("View Student") viSt.geometry("400x400+200+200") viSt.withdraw() stData=scrolledtext.ScrolledText(viSt,width=30,height=5) btnViewBack=Button(viSt,text="Back",command=f4) stData.pack(pady=10) btnViewBack.pack(pady=10) def f7(): root.deiconify() upSt.withdraw() def f10(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entUpRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entUpRno.focus() return ename=entUpName.get() if ename.isalpha(): name=ename else: messagebox.showerror("Error", "Please enter a valid name(string)") entUpName.focus() return cursor=con.cursor() sql="update student1 set name = '%s' where rno = '%d'" args=(name,rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows updated " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() def f11(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entUpRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entUpRno.focus() return emarks=entUpMarks.get() if emarks.isdigit() and int(emarks)>=0 and int(emarks)<101: marks=int(emarks) else: messagebox.showerror("Error", "Please enter marks within limit of 0 to 100") entUpMarks.focus() return cursor=con.cursor() sql="update student1 set marks = '%d' where rno = '%d'" args=(marks,rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows updated " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() upSt=Toplevel(root) upSt.title("Update Student") upSt.geometry("400x400+200+200") upSt.withdraw() lblUpRno=Label(upSt,text="Enter rno ") lblUpName=Label(upSt,text="Update Name ") lblUpMarks=Label(upSt,text="Update Marks ") entUpRno=Entry(upSt,bd=5) entUpName=Entry(upSt,bd=5) entUpMarks=Entry(upSt,bd=5) btnUpName=Button(upSt,text="Update Name",command=f10) btnUpMarks=Button(upSt,text="Update Marks",command=f11) btnUpBack=Button(upSt,text="Back",command=f7) lblUpRno.pack(pady=10) entUpRno.pack(pady=10) lblUpName.pack(pady=10) entUpName.pack(pady=10) lblUpMarks.pack(pady=10) entUpMarks.pack(pady=10) btnUpName.pack(pady=10) btnUpMarks.pack(padx=10) btnUpBack.pack(pady=10) def f9(): root.deiconify() deSt.withdraw() def f12(): con=None cursor=None try: con=cx_Oracle.connect("system/abc123") srno=entDeRno.get() if srno.isdigit() and int(srno)>0: rno=int(srno) else: messagebox.showerror("Error", "Please enter a valid rollno(integer)") entDeRno.focus() return cursor=con.cursor() sql="delete from student1 where rno ='%d'" args=(rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount) +"rows deleted " messagebox.showinfo("Success",msg) except cx_Oracle.DatabaseError as e: con.rollback() print("Failure ",e) finally: if cursor is not None: cursor.close() if con is not None: con.close() deSt=Toplevel(root) deSt.title("Delete Student") deSt.geometry("400x400+200+200") deSt.withdraw() lblDeRno=Label(deSt,text="Enter rno ") entDeRno=Entry(deSt,bd=5) btnDeSave=Button(deSt,text="Delete",command=f12) btnDeBack=Button(deSt,text="Back",command=f9) lblDeRno.pack(pady=10) entDeRno.pack(pady=10) btnDeSave.pack(pady=10) btnDeBack.pack(pady=10) root.mainloop()
f45c4dcc2c24ecc21fc47ebdc36ea32176f81126
[ "Markdown", "Python", "Text" ]
6
Text
akashlhire/Python-based-Student-Management-System
32a728c1feff3cbe3e54424f2cdb82aad253271d
d7ef69b42295844b91b7c606e923f517e2042c31
refs/heads/master
<repo_name>danielmakarzec/rails-mister-cocktail<file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # require 'faker' Ingredient.destroy_all Ingredient.create!(name: 'vodka') Ingredient.create!(name: 'gin') Ingredient.create!(name: 'rum') Ingredient.create!(name: 'whisky') Ingredient.create!(name: 'brandy') Ingredient.create!(name: 'tia maria') Ingredient.create!(name: 'jagermeister') Ingredient.create!(name: 'drambuie') Ingredient.create!(name: 'tequila') Ingredient.create!(name: 'schnapps') Ingredient.create!(name: 'aperol') Ingredient.create!(name: 'pims') Ingredient.create!(name: 'water') Ingredient.create!(name: 'tonic') Ingredient.create!(name: 'coke') Ingredient.create!(name: 'soda') Ingredient.create!(name: 'lemonade') Ingredient.create!(name: 'lime cordial') Ingredient.create!(name: 'black currant cordial') Ingredient.create!(name: 'lime') Ingredient.create!(name: 'lemon') Ingredient.create!(name: 'orange') Ingredient.create!(name: 'cream') Ingredient.create!(name: 'prosecco') <file_sep>/app/javascript/packs/application.js /* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb // Uncomment to copy all static images under ../images to the output folder and reference // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) // or the `imagePath` JavaScript helper below. // // const images = require.context('../images', true) // const imagePath = (name) => images(name, true) //= require rails-ujs // --- edit mode --- const nameToggle = () => { const b = document.querySelector('.edit-btn'); const icon = '<i class="fas fa-pencil-alt"></i>'; if (b.innerText == "Edit me!  ") { b.innerHTML = "<strong>Exit Edit Mode</strong>"; } else { b.innerHTML = "<strong>Edit me!  </strong>"; b.insertAdjacentHTML("beforeend", icon); } }; const edit = document.querySelectorAll('.edit'); const editBtn = document.querySelector('.edit-btn'); editBtn.addEventListener('click', () => { edit.forEach((e) => { e.classList.toggle("my_toggle"); }); nameToggle(); }); <file_sep>/app/models/cocktail.rb class Cocktail < ApplicationRecord has_many :doses, dependent: :destroy has_many :ingredients, through: :doses validates :name, uniqueness: true, presence: true has_one_attached :photo validates :photo, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'] end <file_sep>/README.md # MR Cocktail <p>Ruby / JavaScript / SCSS</p> <h3>Framework:</h3> <pre>"Ruby on Rails": "5.2.4.1"</pre> <h3>DEMO</h3> https://mr-cocktail-318.herokuapp.com
1bcf5ceabdacfde178a306eb19b17f84fa75ee88
[ "JavaScript", "Ruby", "Markdown" ]
4
Ruby
danielmakarzec/rails-mister-cocktail
a68cde0684907e9892f14a8d16604ce3eceda527
b62a3fda3e1f7cca4cc2fbcb18d0b55e786d0718
refs/heads/master
<file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package executions import ( "fmt" "io/ioutil" "os" "strings" "cloud.google.com/go/storage" "golang.org/x/net/context" v1cloudbuild "google.golang.org/api/cloudbuild/v1" "gopkg.in/yaml.v2" ) func LoadBuild(path string) (*v1cloudbuild.Build, error) { efile, err := os.Open(path) if err != nil { return nil, fmt.Errorf("could not open config %q: %v", path, err) } edata, err := ioutil.ReadAll(efile) if err != nil { return nil, fmt.Errorf("could not read config %q: %v", path, err) } b := &v1cloudbuild.Build{} if err := yaml.Unmarshal(edata, b); err != nil { return nil, fmt.Errorf("could not parse config %q: %v", path, err) } return b, nil } type Client struct { ProjectID string Builds *v1cloudbuild.Service Storage *storage.Client } func (c Client) WaitForBuild(ctx context.Context, buildID string) error { return nil } func (c Client) FetchBuildStatus(ctx context.Context, buildID string) (string, error) { return "", nil } func (c Client) FetchBuildLog(ctx context.Context, buildID string) (string, error) { b, err := c.Builds.Projects.Builds.Get(c.ProjectID, buildID).Do() if err != nil { return "", err } logfilePath := fmt.Sprintf("%s/log-%s.txt", b.LogsBucket, b.Id) tokens := strings.SplitN(logfilePath[len("gs://"):], "/", 2) bucket := tokens[0] object := tokens[1] r, err := c.Storage.Bucket(bucket).Object(object).NewReader(ctx) if err != nil { return "", err } d, err := ioutil.ReadAll(r) if err != nil { return "", err } return string(d), nil } <file_sep># coord The `coord` container image coordinates a `flargo` workflow. It listens to a Cloud Pub/Sub topic to keep track of each `flargo` execution, such that only the id of the build running the coord is needed in order to get a view of the entire workflow. For each execution that begins, ends, is retried or skipped, the `coord` build step will write a log message that can be consulted by the `flargo` tool later. For this container image to run as a Container Builder step, the builder service account needs following permissions: - pubsub.subscriptions.consume - pubsub.subscriptions.create - pubsub.topics.attachSubscription - pubsub.topics.create - pubsub.topics.publish <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "fmt" "io" "io/ioutil" "os" "strings" ) /* type ':' name '(' name [ 'as' bar ] ')' file */ type Config struct { Executions []Execution Path string } type Execution struct { Type string Name string Params []Param Path string } type Param struct { Name string } func Load(path string) (*Config, error) { fin, err := os.Open(path) if err != nil { return nil, fmt.Errorf("could not open %q: %v", path, err) } cfg, err := Parse(fin) if err != nil { return nil, fmt.Errorf("could not parse %q: %v", path, err) } cfg.Path = path return cfg, nil } func Parse(r io.Reader) (*Config, error) { data, err := ioutil.ReadAll(r) if err != nil { return nil, err } lines := strings.Split(string(data), "\n") var c Config for lineNumber, l := range lines { s := strings.TrimSpace(l) if s == "" || s[0] == '#' { continue } var e Execution colonStop := strings.Index(s, ":") if colonStop == -1 { return nil, fmt.Errorf("line %d: expected '^<type> :'", lineNumber) } e.Type = strings.TrimSpace(s[:colonStop]) s = strings.TrimSpace(s[colonStop+1:]) parenStop := strings.Index(s, "(") if parenStop == -1 { return nil, fmt.Errorf("line %d: expected 'name ('", lineNumber) } e.Name = strings.TrimSpace(s[:parenStop]) s = strings.TrimSpace(s[parenStop+1:]) parenStop = strings.Index(s, ")") if parenStop == -1 { return nil, fmt.Errorf("line %d: expected '( param, param, ... )'", lineNumber) } ps := s[:parenStop] s = strings.TrimSpace(s[parenStop+1:]) paramTokens := strings.Split(ps, ",") for _, pt := range paramTokens { if pt == "" { break } ptTokens := strings.Fields(pt) var name string name = ptTokens[0] if len(ptTokens) != 1 { return nil, fmt.Errorf("line %d: wrong number of tokens for param %q", lineNumber, pt) } e.Params = append(e.Params, Param{ Name: name, }) } e.Path = s c.Executions = append(c.Executions, e) } names := map[string]bool{} for _, e := range c.Executions { if names[e.Name] { return nil, fmt.Errorf("repeated name %q", e.Name) } names[e.Name] = true } return &c, nil } <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package auth import ( "encoding/json" "fmt" "net/http" "os/exec" "time" "golang.org/x/net/context" "golang.org/x/oauth2" ) type ConfigReport struct { Configuration struct { ActiveConfiguration string `json:"active_configuration"` Properties map[string]map[string]string `json:"properties"` } `json:"configuration"` Credential struct { AccessToken string `json:"access_token"` TokenExpiry string `json:"token_expiry"` } `json:"credential"` } func (cr ConfigReport) GetProperty(section, name string) (string, bool) { s, ok := cr.Configuration.Properties[section] if !ok { return "", false } p, ok := s[name] return p, ok } // An SDKConfig provides access to tokens from an account already // authorized via the Google Cloud SDK. type SDK struct { Account string } // NewSDKConfig creates an SDKConfig for the given Google Cloud SDK // account. If account is empty, the account currently active in // Google Cloud SDK properties is used. // Google Cloud SDK credentials must be created by running `gcloud auth` // before using this function. // The Google Cloud SDK is available at https://cloud.google.com/sdk/. func NewSDK(account string) (*SDK, error) { return &SDK{ Account: account, }, nil } func ReadConfigHelper() (*ConfigReport, error) { cmd := exec.Command("gcloud", "config", "config-helper", "--format=json") // TODO: use specified account //cmd.Env = []string{"CLOUDSDK_CORE_ACCOUNT=" + c.Account} out, err := cmd.Output() if err != nil { return nil, fmt.Errorf("getting gcloud config: %v", err) } cfg := &ConfigReport{} if err := json.Unmarshal(out, cfg); err != nil { return nil, fmt.Errorf("unmarshalling gcloud config: %v", err) } return cfg, nil } func (c *SDK) Token() (*oauth2.Token, error) { cfg, err := ReadConfigHelper() // eg "2017-06-09T20:04:32Z" // rerference time is "Mon Jan 2 15:04:05 -0700 MST 2006" et, err := time.Parse("2006-01-02T15:04:05Z", cfg.Credential.TokenExpiry) if err != nil { return nil, fmt.Errorf("parsing time: %v", err) } t := &oauth2.Token{ AccessToken: cfg.Credential.AccessToken, Expiry: et, } return t, nil } // Client returns an HTTP client using Google Cloud SDK credentials to // authorize requests. The token will acquired from // `gcloud config config-helper` every time, and `gcloud` will be // responsible for refreshing it as needed. func (c *SDK) Client(ctx context.Context) *http.Client { return &http.Client{ Transport: &oauth2.Transport{ Source: c, }, } } <file_sep>#!/bin/bash # Complete a workflow execution. GCS_PREFIX=$1 WORKFLOW_ID=$2 EXECUTION_ID=$3 echo "$ gsutil rsync /workflow_artifacts/out \"$GCS_PREFIX/$EXECUTION_ID/\"" gsutil rsync /workflow_artifacts/out "$GCS_PREFIX/$EXECUTION_ID/" || exit; gcloud beta pubsub topics publish "workflow-$WORKFLOW_ID" "{\"completed\":\"$EXECUTION_ID\"}" <file_sep>mkdir vendor || exit imports=$(go list -f '{{range .Imports}}{{printf "%s\n" .}}{{end}}' ./... | grep -v flargo ) export GOPATH=$PWD/vendor set -x for import in $imports; do go get "$import" || exit done mv vendor/src/* vendor rm -r vendor/src vendor/pkg <file_sep># flargo config ## grammer ``` CONFIG -> EXECUTION* EXECUTION -> EXECUTION_SIGNATURE EXECUTION_BODY EXECUTION_SIGNATURE -> TYPE ':' NAME '(' [ PARAM ( ',' PARAM ) * ] EXECUTION_BODY -> FILE_PATH ``` ### working example ``` # build will begin immediately. exec: build() build.yaml # build will begin immediately. exec: build_probes() probe.yaml # "deploy_to_dev" will only start once "build" is complete. Its "out" files will # be put in "in/build". # This example assumpes that retagging an image is sufficient to deploy. That # is, it assumes that the runtimes are watching for pushes to specific tags. exec: deploy_to_dev(build) deploy_dev.yaml # Once dev is ready, run the probes (built earlier) to check that things are # working. exec: test_dev(deploy_to_dev, build_probes) test_dev.yaml # A wait directive means that a human has to run flargo to indicate this # execution has completed. It's used as a manual gate between dev and prod, # in this example. wait: dev_to_prod(test_dev) - # "deploy_to_prod" will only start once "dev_to_prod" is complete. exec: deploy_to_prod(dev_to_prod) deploy_prod.yaml # Once prod is ready, run the probes (built earlier) to check that things are # working. exec: test_prod(deploy_to_prod, build_probes) test_prod.yaml ``` <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "encoding/json" "reflect" "strings" "testing" ) func TestBasicParse(t *testing.T) { r := strings.NewReader(` # build will begin immediately. exec: build() build.yaml # build will begin immediately. exec: build_probes() probe.yaml # "deploy_to_dev" will only start once "build" is complete. Its "out" files will # be put in "in/build". # This example assumpes that retagging an image is sufficient to deploy. That # is, it assumes that the runtimes are watching for pushes to specific tags. exec: deploy_to_dev(build) deploy_dev.yaml # Once dev is ready, run the probes (built earlier) to check that things are # working. exec: test_dev(deploy_to_dev, build_probes) test_dev.yaml # A wait directive means that a human has to run flargo to indicate this # execution has completed. It's used as a manual gate between dev and prod, # in this example. wait: dev_to_prod(test_dev) - # "deploy_to_prod" will only start once "dev_to_prod" is complete. exec: deploy_to_prod(dev_to_prod) deploy_prod.yaml # Once prod is ready, run the probes (built earlier) to check that things are # working. exec: test_prod(deploy_to_prod, build_probes) test_prod.yaml `) expected := Config{ Executions: []Execution{{ Type: "exec", Name: "build", Path: "build.yaml", }, { Type: "exec", Name: "build_probes", Path: "probe.yaml", }, { Type: "exec", Name: "deploy_to_dev", Params: []Param{{ Name: "build", }}, Path: "deploy_dev.yaml", }, { Type: "exec", Name: "test_dev", Params: []Param{{ Name: "deploy_to_dev", }, { Name: "build_probes", }}, Path: "test_dev.yaml", }, { Type: "wait", Name: "dev_to_prod", Params: []Param{{ Name: "test_dev", }}, Path: "-", }, { Type: "exec", Name: "deploy_to_prod", Params: []Param{{ Name: "dev_to_prod", }}, Path: "deploy_prod.yaml", }, { Type: "exec", Name: "test_prod", Params: []Param{{ Name: "deploy_to_prod", }, { Name: "build_probes", }}, Path: "test_prod.yaml", }}, } config, err := Parse(r) if err != nil { t.Fatal(err) } jdata, _ := json.MarshalIndent(config, " ", " ") t.Logf("%s\n", jdata) if len(config.Executions) != len(expected.Executions) { t.Error("wrong") } else { for i := range expected.Executions { if !reflect.DeepEqual(config.Executions[i], expected.Executions[i]) { t.Errorf("item %d: got\n%+v\nwant:\n%+v\n", i, config.Executions[i], expected.Executions[i]) } } } } <file_sep>FROM gcr.io/cloud-builders/gcloud COPY complete.bash /flargo/complete.bash ENTRYPOINT ["bash", "/flargo/complete.bash"] <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/base64" "encoding/json" "fmt" "io" "log" "os" "path" "path/filepath" "strings" "sync" "cloud.google.com/go/storage" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/iterator" "google.golang.org/api/option" v1pubsub "google.golang.org/api/pubsub/v1" ) type completionMessage struct { Completed string `json:"completed"` Artifacts string `json:"artifacts"` } func usage() { log.Fatalf("Usage: wait GCS_PREFIX WORKFLOW_ID SUBSCRIPTION BLOCKING_EXECUTION*") } func main() { ctx := context.Background() args := os.Args[1:] if len(args) < 3 { usage() } gcsPrefix := args[0] //workflowID := args[1] subscriptionName := args[2] blocks := map[string]bool{} for _, block := range args[3:] { blocks[block] = true } if !strings.HasPrefix(gcsPrefix, "gs://") { log.Fatalf("Invalid GCS prefix %q", gcsPrefix) } bucketObject := gcsPrefix[len("gs://"):] tokens := strings.SplitN(bucketObject, "/", 2) if len(tokens) != 2 { log.Fatalf("Invalid GCS prefix %q", gcsPrefix) } bucket, object := tokens[0], tokens[1] client := oauth2.NewClient(ctx, google.ComputeTokenSource("")) pubsub, err := v1pubsub.New(client) if err != nil { log.Fatalf("Could not create pubsub client: %v", err) } sc, err := storage.NewClient(ctx, option.WithHTTPClient(client)) if err != nil { log.Fatalf("Could not create storage client: %v", err) } // Poll the subscription until the blocks are resolved. for len(blocks) > 0 { resp, err := pubsub.Projects.Subscriptions.Pull(subscriptionName, &v1pubsub.PullRequest{ MaxMessages: 10, }).Do() if err != nil { log.Fatalf("Could not pull from subscription: %v", err) } for _, rmsg := range resp.ReceivedMessages { if _, err := pubsub.Projects.Subscriptions.Acknowledge(subscriptionName, &v1pubsub.AcknowledgeRequest{ AckIds: []string{rmsg.AckId}, }).Do(); err != nil { log.Printf("Could not ack %q: %v", rmsg.AckId, err) } dec := json.NewDecoder(base64.NewDecoder(base64.StdEncoding, strings.NewReader(rmsg.Message.Data))) var cmsg completionMessage if err := dec.Decode(&cmsg); err != nil { log.Printf("Could not decode message: %v", err) } if cmsg.Completed != "" && blocks[cmsg.Completed] { log.Printf("Got completion %+q", cmsg) delete(blocks, cmsg.Completed) // copy the blocking execution's artifacts into this execution. if err := fetchArtifacts(ctx, sc, bucket, object, cmsg.Completed); err != nil { log.Fatalf("Could not fetch artifacts for %q: %v", cmsg.Completed, err) } } } } if err := os.MkdirAll(filepath.Join("/workflow_artifacts", "out"), 0755); err != nil { log.Fatal("could not make artifact out directory") } } func fetchArtifacts(ctx context.Context, sc *storage.Client, bucket, object, block string) error { objItr := sc.Bucket(bucket).Objects(ctx, &storage.Query{ Prefix: path.Join(object, block), }) var wg sync.WaitGroup errCh := make(chan error, 1) for { attrs, err := objItr.Next() if err == iterator.Done { break } if err != nil { return err } objName := attrs.Name wg.Add(1) go func(objName string) { defer wg.Done() r, err := sc.Bucket(bucket).Object(objName).NewReader(ctx) if err != nil { errCh <- fmt.Errorf("could not read object %q: %v", objName, err) return } relpath, err := filepath.Rel(object, objName) if err != nil { errCh <- fmt.Errorf("could not get relative path from %q to %q", object, objName) } localPath := filepath.Join("/workflow_artifacts", "in", relpath) localDir, _ := filepath.Split(localPath) if err := os.MkdirAll(localDir, 0755); err != nil { errCh <- fmt.Errorf("could not create directory for artifact %q: %v", localDir, err) return } fout, err := os.Create(localPath) if err != nil { errCh <- fmt.Errorf("could not create local artifact %q: %v", relpath, err) return } if _, err := io.Copy(fout, r); err != nil { errCh <- fmt.Errorf("could not download artifact %q: %v", relpath, err) return } log.Printf("Downloaded %s to %s", objName, fout.Name()) }(objName) } wg.Wait() close(errCh) for err := range errCh { return err } return nil } <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main // import "github.com/skelterjohn/flargo" import ( "encoding/json" "errors" "flag" "fmt" "log" "path/filepath" "strings" "sync" "time" "cloud.google.com/go/storage" "golang.org/x/net/context" v1cloudbuild "google.golang.org/api/cloudbuild/v1" "google.golang.org/api/googleapi" "google.golang.org/api/option" v1pubsub "google.golang.org/api/pubsub/v1" "github.com/skelterjohn/flargo/auth" "github.com/skelterjohn/flargo/config" "github.com/skelterjohn/flargo/executions" ) func usage() { log.Fatal(`flargo is a tool to run workflows on top of Google Container Engine. Usage: flargo start CONFIG wait FLOW describe FLOW retry FLOW EXECUTION skip FLOW EXECUTION `) } // TODO: configure gcr.io/cloud-workflows/<flargo image> to use customer project registries. func main() { ctx := context.Background() flag.Parse() args := flag.Args() if len(args) < 1 { usage() } switch args[0] { case "start": if len(args) != 2 { usage() } cfgFile := args[1] cfg, err := config.Load(cfgFile) if err != nil { log.Fatalf("Could not parse %q: %v", cfgFile, err) } if err := start(ctx, cfg); err != nil { log.Fatalf("Could not start workflow: %v", err) } } // WAIT PROCESS // Create subscription to watch for completions // Inspect coord logs for completions // Wait for remaining completions on pubsub // DESCRIBE PROCESS // ? // RETRY PROCESS // Cancel existing execution // Begin execution // SKIP PROCESS // Cancel existing execution // Publish completion } func buildFromOp(op *v1cloudbuild.Operation) (*v1cloudbuild.Build, error) { md := struct { T string `json:"@type"` Build *v1cloudbuild.Build `json:"build"` }{} if err := json.Unmarshal(op.Metadata, &md); err != nil { return nil, err } return md.Build, nil } func start(ctx context.Context, cfg *config.Config) error { scfg, err := auth.NewSDK("") if err != nil { return fmt.Errorf("could not find SDK config: %v", err) } ch, err := auth.ReadConfigHelper() if err != nil { return fmt.Errorf("could not read SDK config helper: %v", err) } projectID, ok := ch.GetProperty("core", "project") if !ok { return errors.New("no project property set") } cb, err := v1cloudbuild.New(scfg.Client(ctx)) if err != nil { return fmt.Errorf("could not create cloudbuild client: %v", err) } ps, err := v1pubsub.New(scfg.Client(ctx)) if err != nil { return fmt.Errorf("could not create pubsub client: %v", err) } sc, err := storage.NewClient(ctx, option.WithTokenSource(scfg)) if err != nil { return fmt.Errorf("could not create storage client: %v", err) } executionsClient := executions.Client{ ProjectID: projectID, Builds: cb, Storage: sc, } cfgDir, _ := filepath.Split(cfg.Path) // Load execution configs bconfigs := map[string]*v1cloudbuild.Build{} for _, execution := range cfg.Executions { b, err := executions.LoadBuild(filepath.Join(cfgDir, execution.Path)) if err != nil { return err } bconfigs[execution.Name] = b } // Start coord op, err := cb.Projects.Builds.Create(projectID, &v1cloudbuild.Build{ Steps: []*v1cloudbuild.BuildStep{{ Name: "gcr.io/cloud-workflows/coord", Args: []string{"$BUILD_ID"}, }}, }).Context(ctx).Do() if err != nil { return fmt.Errorf("could not create coord execution: %v", err) } b, err := buildFromOp(op) if err != nil { return fmt.Errorf("could not unmarshal build: %v", err) } workflowID := b.Id log.Printf("Workflow ID: %s", workflowID) // Check the coord execution log to see when it creates the topic. // We can't create the topic before hand because it has the build ID // in it, and we don't know that until the coord execution begins. for { execLog, err := executionsClient.FetchBuildLog(ctx, workflowID) if err != nil && err != storage.ErrObjectNotExist { return fmt.Errorf("could not fetch workflow log: %v", err) } if err == nil && strings.Contains(execLog, "Created topic") { break } time.Sleep(time.Second) } // This topic was created by the coord execution. tname := fmt.Sprintf("workflow-%s", workflowID) workflowTopic := fmt.Sprintf("projects/%s/topics/%s", projectID, tname) log.Printf("worklow topic: %s", workflowTopic) // Ensure a GCS place for artifacts. gcsBucket := fmt.Sprintf("%s_workflow_artifacts", projectID) gcsPrefix := fmt.Sprintf("gs://%s/%s", gcsBucket, workflowID) // Create the bucket. If it exists, ensure that it's owned by this project to avoid artifact theft. if err := sc.Bucket(gcsBucket).Create(ctx, projectID, nil); err != nil { // if 409, fetch the bucket to compare project IDs. gerr, ok := err.(*googleapi.Error) if ok && gerr.Code == 409 { policy, err := sc.Bucket(gcsBucket).IAM().Policy(ctx) if err != nil { return fmt.Errorf("could not check policy of gs://%s: %v", gcsBucket, err) } if !policy.HasRole("projectOwner:"+projectID, "roles/storage.legacyBucketOwner") { jdata, _ := json.MarshalIndent(policy, " ", " ") log.Printf("Artifacts bucket policy:\n%s\n", jdata) return errors.New("artifacts bucket exists, but is owned by someone else") } } else { return fmt.Errorf("could not create artifact bucket: %v", err) } } log.Printf("Artifacts go to %s", gcsPrefix) // For each execution, execErrors := make(chan error, len(cfg.Executions)) var execWG sync.WaitGroup for i, execution := range cfg.Executions { execWG.Add(1) go func(i int, execution config.Execution) { defer execWG.Done() // - Create subscription sname := fmt.Sprintf("workflow-%s-%d", workflowID, i) executionSubscription := fmt.Sprintf("projects/%s/subscriptions/%s", projectID, sname) log.Printf("%q execution subscription: %s", execution.Name, sname) if _, err := ps.Projects.Subscriptions.Create(executionSubscription, &v1pubsub.Subscription{ Name: sname, Topic: workflowTopic, }).Do(); err != nil { execErrors <- fmt.Errorf("could not create %q subscription: %v", execution.Name, err) return } var waitExecutions []string for _, param := range execution.Params { waitExecutions = append(waitExecutions, param.Name) } // - Augment steps with wait/complete build := bconfigs[execution.Name] build.Steps = append([]*v1cloudbuild.BuildStep{{ Name: "gcr.io/cloud-workflows/wait", Args: append( []string{ gcsPrefix, workflowID, executionSubscription, }, waitExecutions..., ), }}, build.Steps...) build.Steps = append(build.Steps, &v1cloudbuild.BuildStep{ Name: "gcr.io/cloud-workflows/complete", Args: []string{ gcsPrefix, workflowID, execution.Name, }, }, ) // Ensure that each step (including wait and complete) have access to the artifacts volume. // The artifacts will be populated by wait, and will be copied out by complete. for _, b := range build.Steps { b.Volumes = append(b.Volumes, &v1cloudbuild.Volume{ Name: "workflow_artifacts", Path: "/workflow_artifacts", }) } // - Begin execution op, err := cb.Projects.Builds.Create(projectID, build).Context(ctx).Do() if err != nil { execErrors <- fmt.Errorf("could not create %q execution: %v", execution.Name, err) return } if executionBuild, err := buildFromOp(op); err != nil { execErrors <- fmt.Errorf("could not understand %q execution: %v", execution.Name, err) return } else { log.Printf("%q execution is build %s", execution.Name, executionBuild.Id) } }(i, execution) } execWG.Wait() close(execErrors) for err := range execErrors { return err } return nil } type coord struct { } func startCoord() (*coord, error) { return nil, nil } func getCoord(workflowID string) (*coord, error) { return nil, nil } <file_sep>/* Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/base64" "fmt" "io" "log" "os" "strings" "time" "cloud.google.com/go/compute/metadata" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" pubsub_v1 "google.golang.org/api/pubsub/v1" ) /* The coord program listens for certain kinds of messages on a pubsub subscription (which must already exist), and prints them to stdout so that they can be reviewed by flargo. */ func init() { // Because the metadata package can't figure this out itself. os.Setenv("GCE_METADATA_HOST", "metadata.google.internal") } func main() { ctx := context.Background() if len(os.Args) != 2 { fmt.Println("Usage: %s ID", os.Args[0]) } workflowID := os.Args[1] projectID, err := metadata.ProjectID() if err != nil { log.Fatalf("Could not get project ID") } client := oauth2.NewClient(ctx, google.ComputeTokenSource("")) pubsub, err := pubsub_v1.New(client) if err != nil { log.Fatalf("Could not create pubsub client: %v", err) } tname := fmt.Sprintf("projects/%s/topics/workflow-%s", projectID, workflowID) if _, err := pubsub.Projects.Topics.Create(tname, &pubsub_v1.Topic{ Name: workflowID, }).Do(); err != nil { log.Fatalf("Could not create topic: %v", err) } log.Printf("Created topic %q", tname) sname := fmt.Sprintf("projects/%s/subscriptions/coord-%s", projectID, workflowID) if _, err := pubsub.Projects.Subscriptions.Create(sname, &pubsub_v1.Subscription{ Name: "coord-" + workflowID, Topic: tname, }).Do(); err != nil { log.Fatalf("Could not create subscription: %v", err) } for { time.Sleep(1 * time.Second) resp, err := pubsub.Projects.Subscriptions.Pull(sname, &pubsub_v1.PullRequest{ MaxMessages: 1, }).Do() if err != nil { log.Printf("Error pulling subscription %q: %v", sname, err) continue } for _, rmsg := range resp.ReceivedMessages { // ack rmsg.AckId msg := rmsg.Message.Data io.Copy(os.Stdout, base64.NewDecoder(base64.StdEncoding, strings.NewReader(msg))) fmt.Println() if _, err := pubsub.Projects.Subscriptions.Acknowledge(sname, &pubsub_v1.AcknowledgeRequest{ AckIds: []string{rmsg.AckId}, }).Do(); err != nil { log.Printf("Failed to ack message %q: %v", rmsg.AckId, err) } } } } <file_sep># flargo Resumable dynamic workflows on top of Google Container Builder (or cloudbuild for short). ## how it works The cloudbuild service provides units of execution as a series of steps. This unit of execution is called a "build" by the cloudbuild service, but in reality it's an arbitrary execution with some tooling to make it easy to use for building container images. For a build to succeed, every step in the build must succeed. If a step fails, you cannot skip it or retry. `flargo` creates a workflow pipeline on top of the cloudbuild service. In a `flargo` config file, you specify a set of builds and their dependencies. The `flargo` command line will use the cloudbuild service to run these builds, where the first step is "wait for my dependencies". At any point a particular build can be retried or skipped. When builds in the workflow complete, they publish on Google Cloud Pub/Sub (or pubsub for short). Other builds wait for their dependencies by subscribing to the workflow pubsub topic. Skipping is done by canceling a build (if needed) and sending the `done` message on pubsub directly. Retrying a build is done by canceling the previous attempt (if needed) and creating a new build that will send the message when complete. You can keep track of a particular `flargo` workflow by using the workflow ID. This ID corresponds to a cloudbuild build ID that is used as a kickoff point for execution, and that build's logs provide information to the `flargo` tool in order to allow it to manage things later. Any docker images built by a `flargo` build will be pulled into the next builds in the pipeline. If a `flargo` build, files to be sent to the next builds need to be written to a directory named `out`. Files from earlier builds will be available in `in/$EXECUTION_NAME`. `flargo` will store these intermediate files in Google Cloud Storage(GCS). The current directory will be sent as the source for each `flargo` build, with the `in` and `out` directories put in afterwards (so don't use those directories). ## auth and project settings `flargo` bootstraps on `gcloud` auth and its project property. ## terminology Each `flargo` "item" is called an "execution". An execution corresponds to a single cloudbuild build. A `flargo` config is a list of executions and their dependencies. ## config ### syntax Each execution is specified as follows. ``` <type>: <name>([<dependency>(,<dependency>)*) { <execution config> } ``` `type` may be "exec" or "wait". `name` is an identifier for the execution. `dependency` is the name of some other execution, defined earlier in the config file. It may be aliased like `foo as bar` to have a depdenecy named `foo` appear in the execution as `bar`. `execution config` is whatever config is appropriate for the execution. For `exec`, it's a yaml document appropriate for cloudbuild. For "wait", it is empty. Lines beginning with `#` are comments. ### working example ``` # build will begin immediately. exec: build() build.yaml #steps: #- name: 'gcr.io/cloud-builders/golang-project:alpine' # args: ['service', '--tag=gcr.io/$PROJECT_ID/service'] #images: ['gcr.io/$PROJECT_ID/service'] # build will begin immediately. exec: build_probes() probes.yaml # steps: # - name: 'gcr.io/cloud-builders/docker' # args: ['build', '--tag=gcr.io/$PROJECT_ID/probes', 'probes'] # images: ['gcr.io/$PROJECT_ID/probes'] # "deploy_to_dev" will only start once "build" is complete. Its "out" files will # be put in "in/build". # This example assumpes that retagging an image is sufficient to deploy. That # is, it assumes that the runtimes are watching for pushes to specific tags. exec: deploy_to_dev(build) deploy_dev.yaml # steps: # - name: 'gcr.io/cloud-builders/docker' # args: ['tag', '-f', 'gcr.io/$PROJECT_ID/service', 'gcr.io/$PROJECT_ID/service:dev'] # images: ['gcr.io/$PROJECT_ID/service:dev'] # Once dev is ready, run the probes (built earlier) to check that things are # working. exec: test_dev(deploy_to_dev, build_probes) test_dev.yaml # steps: # - name: 'gcr.io/$PROJECT_ID/probes' # args: ['dev'] # A wait directive means that a human has to run flargo to indicate this # execution has completed. It's used as a manual gate between dev and prod, # in this example. wait: dev_to_prod(test_dev) - # "deploy_to_prod" will only start once "dev_to_prod" is complete. exec: deploy_to_prod(dev_to_prod) deploy_prod.yaml #steps: # - name: 'gcr.io/cloud-builders/docker' # args: ['tag', '-f', 'gcr.io/$PROJECT_ID/service:dev', 'gcr.io/$PROJECT_ID/service:prod'] # images: ['gcr.io/$PROJECT_ID/service:prod'] # Once prod is ready, run the probes (built earlier) to check that things are # working. exec: test_prod(deploy_to_prod, build_probes) test_prod.yaml # steps: # - name: 'gcr.io/$PROJECT_ID/probes' # args: ['prod'] ```
69081bb589ef78d842f705ff69fc2f8861a486aa
[ "Markdown", "Go", "Dockerfile", "Shell" ]
13
Go
rimusz/flargo
9f7f5bb7fb066a2e75cbf14949b913888c893dc8
34fb6c7668faec68a724e796976891fd9e6e50c7
refs/heads/release-2.1.0
<file_sep>/** * PersistentStoreCoordinator.swift * * Copyright 2015 <NAME> * * 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. * * Created by <NAME> on 12/8/15. */ import Foundation import CoreData import TraceLog open class PersistentStoreCoordinator : NSPersistentStoreCoordinator { // The internal write ahead log for logging transactions fileprivate let writeAheadLog: WriteAheadLog? override public convenience init(managedObjectModel model: NSManagedObjectModel) { self.init(managedObjectModel: model, enableLogging: true) } init(managedObjectModel model: NSManagedObjectModel, enableLogging: Bool) { logInfo { "Initializing instance..." } if enableLogging { // // Figure out where to put things // let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] // // Create our write ahead logger // do { writeAheadLog = try WriteAheadLog(identifier: model.uniqueIdentifier(), path: cachePath) } catch { writeAheadLog = nil logError { "Failed to enable logging." } } } else { writeAheadLog = nil logInfo { "Logging is diabled." } } super.init(managedObjectModel: model) logInfo { "Instance initialized." } } override open func addPersistentStore(ofType storeType: String, configurationName configuration: String?, at storeURL: URL?, options: [AnyHashable: Any]?) throws -> NSPersistentStore { logInfo { "Attaching persistent store for type: \(storeType) at path: \(storeURL?.absoluteString)..." } var persistentStore: NSPersistentStore? = nil; do { persistentStore = try super.addPersistentStore(ofType: storeType, configurationName: configuration, at: storeURL, options: options) logInfo { "Persistent Store attached." } } catch let error as NSError { logError { "Failed to attach persistent store: \(error.localizedDescription)" } throw error } return persistentStore! } override open func remove(_ store: NSPersistentStore) throws { logInfo { "Removing persistent store for type: \(store.type) at path: \(store.url)..." } try super.remove(store) logInfo { "Persistent Store removed." } } override open func execute(_ request: NSPersistentStoreRequest, with context: NSManagedObjectContext) throws -> Any { switch (request.requestType) { case NSPersistentStoreRequestType.saveRequestType: fallthrough case NSPersistentStoreRequestType.batchUpdateRequestType: if let log = self.writeAheadLog { // // Obtain permanent IDs for all inserted objects // try context.obtainPermanentIDs(for: [NSManagedObject](context.insertedObjects)) // // Log the changes from the context in a transaction // let transactionID = try log.logTransactionForContextChanges(context) // // Save the main context // do { let results = try super.execute(request, with:context) return results; } catch { log.removeTransaction(transactionID) throw error } } else { fallthrough } case NSPersistentStoreRequestType.fetchRequestType: fallthrough default: return try super.execute(request, with:context) } } } <file_sep>/** * MetaLogEntry.swift * * Copyright 2015 <NAME> * * 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. * * Created by <NAME> on 12/10/15. */ import Foundation import CoreData internal typealias TransactionID = String @objc internal enum MetaLogEntryType: Int32 { case beginMarker = 1 case endMarker = 2 case insert = 3 case update = 4 case delete = 5 } @objc(MetaLogEntry) internal class MetaLogEntry: NSManagedObject { class LogEntryUpdateData : NSObject, NSCoding { required convenience init?(coder aDecoder: NSCoder) { self.init() } func encode(with aCoder: NSCoder) { } } /** NOTE: the attributes in this class are all public because it is considered a structure. We had to make this a class to suite the CoreData requirements. */ class MetaLogEntryInsertData : LogEntryUpdateData { var attributesAndValues: [String : AnyObject]? required convenience init?(coder aDecoder: NSCoder) { self.init() attributesAndValues = aDecoder.decodeObject() as? [String : AnyObject] } override func encode(with aCoder: NSCoder) { aCoder.encode(attributesAndValues) } } class MetaLogEntryUpdateData : LogEntryUpdateData { var attributesAndValues: [String : AnyObject]? var updatedAttributes: [String]? required convenience init?(coder aDecoder: NSCoder) { self.init() attributesAndValues = aDecoder.decodeObject() as? [String : AnyObject] updatedAttributes = aDecoder.decodeObject() as? [String] } override func encode(with aCoder: NSCoder) { aCoder.encode(attributesAndValues) aCoder.encode(updatedAttributes) } } class MetaLogEntryDeleteData : LogEntryUpdateData { required convenience init?(coder aDecoder: NSCoder) { self.init() } override func encode(with aCoder: NSCoder) {} } } <file_sep>/** * MetaLogEntry+CoreDataProperties.swift * * Copyright 2015 <NAME> * * 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. * * Created by <NAME> on 12/10/15. */ import Foundation import CoreData internal extension MetaLogEntry { @NSManaged var sequenceNumber: Int32 @NSManaged var previousSequenceNumber: Int32 @NSManaged var transactionID: TransactionID? @NSManaged var timestamp: TimeInterval @NSManaged var type: MetaLogEntryType @NSManaged var updateEntityName: String? @NSManaged var updateObjectID: String? @NSManaged var updateUniqueID: String? @NSManaged var updateData: LogEntryUpdateData? } <file_sep>/// /// Configuration.swift /// /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 6/22/15. /// import TraceLog // Default values for override methods public let defaultBundleKey = "CCConfiguration" public let defaultDefaults = [String: AnyObject]() /** Main Configuration implementation */ open class Configuration<P: NSObjectProtocol> { /** * This method should return a dictionary keyed by property name * with the values for defaults in the instance. Value types must * be of the correct type for the property or be able to be converted * to the correct type. */ open class func defaults () -> [String: AnyObject] { return defaultDefaults } /** * This method should return the name of the main bundle dictionary * key to search for the configuration option keys. * * @default TCCConfiguration */ open class func bundleKey () -> String { return defaultBundleKey } /** Creates an implementation and instance of an object for the protocol (P) specified. - Parameters - defaults: A dictionary of property names and default values for those properties. - bundleKey: The key used to store the property names and values in the Info.plist file. The value of the key must be a dictionary. - Returns: An instance of an Object that implements the protocol specified by P. */ public final class func instance(_ defaults: [String: AnyObject]? = nil, bundleKey: String? = nil) -> P { // Lookup the protocol in the Objective-C runtime to get the Protocol object pointer guard let conformingProtocol: Protocol = objc_getProtocol(String(reflecting: P.self)) else { fatalError ("Could not create instance for protoocol \(P.self)") } let defaults = defaults ?? self.defaults() let bundleKey = bundleKey ?? self.bundleKey() return createInstance(conformingProtocol, defaults: defaults, bundleKey: bundleKey) as! P } } @objc open class CCConfiguration : NSObject { /** Creates an implementation and instance of an object for the protocol (P) specified. - Parameters - objcProtocol: A configuration Protocol to create an instance for. A class will be created that implements this protocol. - Returns: An instance of an Object that implements the protocol specified by objcProtocol. */ @objc public final class func configurationForProtocol (_ objcProtocol: Protocol) -> AnyObject? { return createInstance(objcProtocol, defaults: defaultDefaults, bundleKey: defaultBundleKey) } /** Creates an implementation and instance of an object for the protocol (P) specified. - Parameters - objcProtocol: A configuration Protocol to create an instance for. A class will be created that implements this protocol. - defaults: A dictionary of property names and default values for those properties. - Returns: An instance of an Object that implements the protocol specified by objcProtocol. */ @objc public final class func configurationForProtocol (_ objcProtocol: Protocol, defaults: [String: AnyObject]) -> AnyObject? { return createInstance(objcProtocol, defaults: defaults, bundleKey: defaultBundleKey) } /** Creates an implementation and instance of an object for the protocol (P) specified. - Parameters - objcProtocol: A configuration Protocol to create an instance for. A class will be created that implements this protocol. - defaults: A dictionary of property names and default values for those properties. - bundleKey: The key used to store the property names and values in the Info.plist file. The value of the key must be a dictionary. - Returns: An instance of an Object that implements the protocol specified by objcProtocol. */ @objc public final class func configurationForProtocol (_ objcProtocol: Protocol, defaults: [String: AnyObject], bundleKey: String) -> AnyObject? { return createInstance(objcProtocol, defaults: defaults, bundleKey: bundleKey) } } /** Internal load exstension */ private enum Errors: Error { case failedInitialization(message: String) } private func createInstance(_ conformingProtocol: Protocol, defaults: [String: AnyObject], bundleKey: String) -> AnyObject { guard let config = CCObject.instance(for: conformingProtocol, defaults: defaults, bundleKey: bundleKey) as? NSObject else { fatalError ("Could not create instance for protoocol \(NSStringFromProtocol(conformingProtocol))") } do { try loadObject(conformingProtocol, anObject: config, bundleKey: bundleKey, defaults: defaults) return config } catch Errors.failedInitialization(let message) { fatalError (message) } catch { fatalError ("\(error)") } } private func loadObject(_ conformingProtocol: Protocol, anObject: NSObject, bundleKey: String, defaults: [AnyHashable: Any]) throws { var errorString = String() let values = Bundle.main.infoDictionary?[bundleKey] as? [AnyHashable: Any] if values == nil { logWarning { "Bundle key \(bundleKey) missing from Info.plist file or is an invalid type. The type must be a dictionary." } } var propertyCount: UInt32 = 0 let properties = protocol_copyPropertyList(conformingProtocol, &propertyCount) defer { properties?.deinitialize(count: Int(propertyCount)) properties?.deallocate() } for index in 0..<propertyCount { let property = properties?[Int(index)] if let propertyName = String(validatingUTF8: property_getName(property!)) { if let value = values?[propertyName] { anObject.setValue(value, forKey: propertyName) } else if let value = defaults[propertyName] { anObject.setValue(value, forKey: propertyName) } else { if errorString.count == 0 { errorString += "The following keys were missing from the info.plist and no default was supplied, a value is required.\r" } errorString += "\t\(propertyName)\r" } } } if errorString.count > 0 { logError { errorString } throw Errors.failedInitialization(message: "Failed to load \(String(describing: anObject)) for protocol \(String(describing: conformingProtocol)), Required values were missing from the info.plist and no default values were found.") } } <file_sep>// // CoherenceTestUtilities.swift // Coherence // // Created by <NAME> on 10/31/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation internal func cachesDirectory() throws -> URL { let fileManager = FileManager.default return try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) } internal func removePersistentStoreCache() throws { let fileManager = FileManager.default let files = try fileManager.contentsOfDirectory(at: cachesDirectory(), includingPropertiesForKeys: [.nameKey], options: .skipsHiddenFiles) for file in files { try fileManager.removeItem(at: file) } } internal func persistentStoreDate(storePrefix: String, storeType: String, configuration: String? = nil) throws -> Date { let storePath = try cachesDirectory().appendingPathComponent("\(storePrefix)\(configuration ?? "").\(storeType)").path let attributes = try FileManager.default.attributesOfItem(atPath: storePath) guard let date = attributes[FileAttributeKey.creationDate] as? Date else { throw NSError(domain: "TestErrorDomain", code: 100, userInfo: [NSLocalizedDescriptionKey: "No creation date returned"]) } return date } internal func persistentStoreExists(storePrefix: String, storeType: String, configuration: String? = nil) throws -> Bool { let storePath = try cachesDirectory().appendingPathComponent("\(storePrefix)\(configuration ?? "").\(storeType)").path return FileManager.default.fileExists(atPath: storePath) } internal func deletePersistentStoreFilesIfExist(storePrefix: String, storeType: String, configuration: String? = nil) throws { let storeDirectory = try cachesDirectory() let storePath = storeDirectory.appendingPathComponent("\(storePrefix)\(configuration ?? "").\(storeType)").path let storeShmPath = "\(storePath)-shm" let storeWalPath = "\(storePath)-wal" try deleteIfExists(fileURL: URL(fileURLWithPath: storePath)) try deleteIfExists(fileURL: URL(fileURLWithPath: storeShmPath)) try deleteIfExists(fileURL: URL(fileURLWithPath: storeWalPath)) } internal func deleteIfExists(fileURL url: URL) throws { let fileManager = FileManager.default let path = url.path if fileManager.fileExists(atPath: path) { try fileManager.removeItem(at: url) } } <file_sep>source 'https://github.com/CocoaPods/Specs.git' use_frameworks! platform :ios, '9.0' target 'Coherence' do pod "Coherence", :path => "../" end target 'Tests' do pod "Coherence", :path => "../" end <file_sep>/// /// TestModel3.swift /// /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 10/31/16. /// import Foundation import CoreData internal class TestModel3: NSManagedObjectModel { override init() { super.init() let userEntity = self.userEntity() let roleEntity = self.roleEntity() self.entities = [userEntity, roleEntity] self.setEntities([userEntity], forConfigurationName: "PersistentEntities") self.setEntities([userEntity], forConfigurationName: "TransientEntities") self.versionIdentifiers = [3] } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func userEntity() -> NSEntityDescription { var attributes = [NSAttributeDescription]() var attribute = NSAttributeDescription() attribute.name = "firstName" attribute.isOptional = true attribute.attributeType = NSAttributeType.stringAttributeType attributes.append(attribute) attribute = NSAttributeDescription() attribute.name = "lastName" attribute.isOptional = true attribute.attributeType = NSAttributeType.stringAttributeType attributes.append(attribute) attribute = NSAttributeDescription() attribute.name = "userName" attribute.isOptional = false attribute.attributeType = NSAttributeType.stringAttributeType attributes.append(attribute) let entity = NSEntityDescription() entity.name = "User" entity.managedObjectClassName = "User" entity.properties = attributes return entity; } fileprivate func roleEntity() -> NSEntityDescription { var attributes = [NSAttributeDescription]() var attribute = NSAttributeDescription() attribute.name = "name" attribute.isOptional = false attribute.attributeType = NSAttributeType.stringAttributeType attributes.append(attribute) attribute = NSAttributeDescription() attribute.name = "description" attribute.isOptional = true attribute.attributeType = NSAttributeType.stringAttributeType attributes.append(attribute) let entity = NSEntityDescription() entity.name = "Role" entity.managedObjectClassName = "NSManagedObject" entity.properties = attributes return entity; } } <file_sep>source 'https://rubygems.org' gem 'cocoapods', '1.4' gem 'xcpretty', '~> 0.2' <file_sep># Change Log All significant changes to this project will be documented in this file. ## [2.1.0](https://github.com/tonystone/coherence/releases/tag/2.1.0) #### Changes - Changed minimum deployment target on iOS to 9.0. - Updated to Swift 4.1. - Expanded TraceLog Cocopaods compatible versions to include < 5.0 (>= 2.0 && < 5.0). ## [2.0.3](https://github.com/tonystone/coherence/releases/tag/2.0.3) #### Added - Opening up persistentStoreCoordinator and managedObjectModel so they are accessible publicly. #### Updated - Fixing crash when TraceLog level is set to TRACE4 (it prints a message using an @escaping closure). #### Removed - Removal of Connect (pre-release) in the CocoaPod spec. ## [2.0.2](https://github.com/tonystone/coherence/releases/tag/2.0.2) #### Changes - Reorganized internally to contain Connect (pre-release). ## [2.0.1](https://github.com/tonystone/coherence/releases/tag/2.0.1) - First release to CocoaPods master repo. #### Changes - None ## [2.0.0](https://github.com/tonystone/coherence/releases/tag/2.0.0) #### Added - Swift 3 support. - Swift Package Manager Support. - This CHANGELOG.md file. #### Updated - Changed from Swift 2.0 to Swift 3. - Changed from CocoaPods 0.39.0 to 1.1.0. - Change CoreDataStack init methods to throw instead of be failable. - Changed default Info.plist key to CCConfiguration. - Changed CCOverwriteIncompatibleStore to overwriteIncompatibleStore - Changed to TraceLog 2.0. #### Removed - Removed PersistentStoreCoordinator until the remainder of the implementation is complete. - Removed WriteAhead log (for the same reason as above) <file_sep># # Be sure to run `pod lib lint Coherence.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "Coherence" s.version = "2.1.0" s.summary = "Coherence" s.description = <<-DESC Coherence is a collection of base frameworks that help set the groundwork for module development. DESC s.homepage = "https://github.com/tonystone/coherence" s.license = 'Apache License, Version 2.0' s.author = "<NAME>" s.source = { :git => "https://github.com/TheClimateCorporation/coherence-2-x-swift-4.git", :tag => s.version.to_s } s.platform = :ios, '9.0' s.requires_arc = true s.module_name = 'Coherence' s.default_subspecs = ['Configuration', 'Stack'] s.subspec 'ConfigurationCore' do |sp| sp.requires_arc = false sp.source_files = 'Sources/ConfigurationCore/**/*' end s.subspec 'Configuration' do |sp| sp.dependency 'Coherence/ConfigurationCore' sp.source_files = 'Sources/Configuration/*' end s.subspec 'Stack' do |sp| sp.source_files = 'Sources/Stack/*' end s.dependency 'TraceLog', ">= 2.0", "< 5.0" s.dependency 'TraceLog/ObjC', ">= 2.0", "< 5.0" end <file_sep>/// /// Package.swift /// /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 10/30/16. /// import PackageDescription let package = Package( name: "Coherence", /// Note: Currently only cache is supported in SPM due to the fact that TraceLog does not export it's ObjC code to SPM targets: [ Target( name: "Coherence", dependencies: [])], dependencies: [.Package(url: "https://github.com/tonystone/tracelog.git", majorVersion: 2)], exclude: ["_Pods.xcodeproj", "Coherence.podspec", "Docs", "Example", "Scripts","Sources/Coherence/Configuration.swift","Tests/CoherenceTests/ConfigurationTests.swift", "Sources/ConfigurationCore","Tests/ConfigurationCoreTests", "Tests/Test Data", "Tests/en.lproj"] ) /// Added the modules to a framework module let dylib = Product(name: "Coherence", type: .Library(.Dynamic), modules: ["Coherence"]) products.append(dylib) <file_sep>// // Tests-Bridging-Header.h // Coherence // // Created by <NAME> on 1/25/16. // Copyright © 2016 <NAME>. All rights reserved. // #ifndef Tests_Bridging_Header_h #define Tests_Bridging_Header_h #endif /* Tests_Bridging_Header_h */ <file_sep>/** * WriteAheadLog.swift * * Copyright 2015 <NAME> * * 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. * * Created by <NAME> on 12/9/15. */ import Foundation import CoreData import TraceLog internal enum WriteAheadLogErrors: Error { case persistentStoreCreationError(message: String) case failedToAddPersistentStore(message: String) case failedToObtainPermanentIDs(message: String) case transactionWriteFailed(message: String) } internal let MetaLogEntryName = "MetaLogEntry" internal let persistentStoreType = NSSQLiteStoreType internal let sqliteFileExts = ["sqlite", "sqlite-shm", "sqlite-wal"] internal let metaModel = MetaModel() internal class WriteAheadLog { fileprivate typealias CoreDataStackType = GenericCoreDataStack<NSPersistentStoreCoordinator, NSManagedObjectContext> fileprivate let coreDataStack: CoreDataStackType! var nextSequenceNumber = 0 init(identifier: String, path: String) throws { logInfo { "Initializing instance..." } coreDataStack = try CoreDataStackType(managedObjectModel: metaModel, storeNamePrefix: "meta", logTag: String(describing: WriteAheadLog.self)) nextSequenceNumber = try self.lastLogEntrySequenceNumber() + 1 logTrace(1) { "Starting Transaction ID: \(self.nextSequenceNumber)" } logInfo { "Instance initialized." } } fileprivate func lastLogEntrySequenceNumber () throws -> Int { objc_sync_enter(self) defer { objc_sync_exit(self) } let metadataContext = coreDataStack.editContext // // We need to find the last log entry and get it's // sequenceNumber value to calculate the next number // in the database. // let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MetaLogEntryName) fetchRequest.fetchLimit = 1 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sequenceNumber", ascending:false)] if let lastLogRecord = try (metadataContext().fetch(fetchRequest).last) as? MetaLogEntry { return Int(lastLogRecord.sequenceNumber) } return 0 } internal func nextSequenceNumberBlock(_ size: Int) -> ClosedRange<Int> { objc_sync_enter(self) defer { objc_sync_exit(self) } let sequenceNumberBlockStart = nextSequenceNumber nextSequenceNumber = nextSequenceNumber + size - 1 return sequenceNumberBlockStart...size - 1 } internal func logTransactionForContextChanges(_ transactionContext: NSManagedObjectContext) throws -> TransactionID { // // NOTE: This method must be reentrent. Be sure to use only stack variables asside from // the protected access method nextSequenceNumberBlock // let inserted = transactionContext.insertedObjects let updated = transactionContext.updatedObjects let deleted = transactionContext.deletedObjects // // Get a block of sequence numbers to use for the records // that need recording. // // Sequence number = begin + end + inserted + updated + deleted // let sequenceNumberBlock = self.nextSequenceNumberBlock(2 + inserted.count + updated.count + deleted.count) var sequenceNumber = sequenceNumberBlock.lowerBound var transactionID: TransactionID? = nil var writeError: NSError? = nil let metadataContext = coreDataStack.editContext() metadataContext.performAndWait { do { transactionID = try self.logBeginTransactionEntry(metadataContext, sequenceNumber: &sequenceNumber) if let unwrappedTransactionID = transactionID { self.logInsertEntries(inserted, transactionID: unwrappedTransactionID, metadataContext: metadataContext, sequenceNumber: &sequenceNumber) self.logUpdateEntries(updated, transactionID: unwrappedTransactionID, metadataContext: metadataContext, sequenceNumber: &sequenceNumber) self.logDeleteEntries(deleted, transactionID: unwrappedTransactionID, metadataContext: metadataContext, sequenceNumber: &sequenceNumber) try self.logEndTransactionEntry(unwrappedTransactionID, metadataContext: metadataContext, sequenceNumber: &sequenceNumber) if metadataContext.hasChanges { try metadataContext.save() } } } catch let error as NSError { writeError = error } } if let unwrappedWriteError = writeError { throw WriteAheadLogErrors.transactionWriteFailed(message: unwrappedWriteError.localizedDescription) } return transactionID! } internal func removeTransaction(_ transactionID: TransactionID) { } internal func transactionLogEntriesForTransaction(_ transactionID: TransactionID, context: NSManagedObjectContext) -> [MetaLogEntry] { return [] } internal func transactionLogRecordsForEntity(_ entityDescription: NSEntityDescription, context: NSManagedObjectContext) throws -> [MetaLogEntry] { let fetchRequest = NSFetchRequest<NSManagedObject>() fetchRequest.entity = NSEntityDescription.entity(forEntityName: MetaLogEntryName, in: context) fetchRequest.predicate = NSPredicate(format: "updateEntityName == %@", entityDescription.name!) return try context.fetch(fetchRequest) as! [MetaLogEntry] } fileprivate func logBeginTransactionEntry(_ metadataContext: NSManagedObjectContext, sequenceNumber: inout Int) throws -> TransactionID { let metaLogEntry = NSEntityDescription.insertNewObject(forEntityName: MetaLogEntryName, into: metadataContext) as! MetaLogEntry do { try metadataContext.obtainPermanentIDs(for: [metaLogEntry]) } catch let error as NSError { throw WriteAheadLogErrors.failedToObtainPermanentIDs(message: "Failed to obtain perminent id for transaction log record: \(error.localizedDescription)") } // // We use the URI representation of the object id as the transactionID // let transactionID = metaLogEntry.objectID.uriRepresentation().absoluteString metaLogEntry.transactionID = transactionID metaLogEntry.sequenceNumber = Int32(sequenceNumber) metaLogEntry.previousSequenceNumber = Int32(sequenceNumber - 1) metaLogEntry.type = MetaLogEntryType.beginMarker metaLogEntry.timestamp = Date().timeIntervalSinceNow // // Increment the sequence for this record // sequenceNumber += 1 logTrace(4) { "Log entry created: \(metaLogEntry)" } return transactionID } fileprivate func logEndTransactionEntry(_ transactionID: TransactionID, metadataContext: NSManagedObjectContext, sequenceNumber: inout Int) throws { let metaLogEntry = NSEntityDescription.insertNewObject(forEntityName: MetaLogEntryName, into: metadataContext) as! MetaLogEntry metaLogEntry.transactionID = transactionID metaLogEntry.sequenceNumber = Int32(sequenceNumber) metaLogEntry.previousSequenceNumber = Int32(sequenceNumber - 1) metaLogEntry.type = MetaLogEntryType.endMarker metaLogEntry.timestamp = Date().timeIntervalSinceNow // // Increment the sequence for this record // sequenceNumber += 1 logTrace(4) { "Log entry created: \(metaLogEntry)" } } fileprivate func logInsertEntries(_ insertedRecords: Set<NSManagedObject>, transactionID: TransactionID, metadataContext: NSManagedObjectContext, sequenceNumber: inout Int) { for object in insertedRecords { let metaLogEntry = self.transactionLogEntry(MetaLogEntryType.insert, object: object, transactionID: transactionID, metadataContext: metadataContext, sequenceNumber: sequenceNumber) // // Get the object attribute change data // let data = MetaLogEntry.MetaLogEntryInsertData() let attributes = [String](object.entity.attributesByName.keys) data.attributesAndValues = object.dictionaryWithValues(forKeys: attributes) as [String : AnyObject] metaLogEntry.updateData = data // // Increment the sequence for this record // sequenceNumber += 1 logTrace(4) { "Log entry created: \(metaLogEntry)" } } } fileprivate func logUpdateEntries(_ updatedRecords: Set<NSManagedObject>, transactionID: TransactionID, metadataContext: NSManagedObjectContext, sequenceNumber: inout Int) { for object in updatedRecords { let metaLogEntry = self.transactionLogEntry(MetaLogEntryType.update, object: object, transactionID: transactionID, metadataContext: metadataContext, sequenceNumber: sequenceNumber) // // Get the object attribute change data // let data = MetaLogEntry.MetaLogEntryUpdateData() let attributes = [String](object.entity.attributesByName.keys) data.attributesAndValues = object.dictionaryWithValues(forKeys: attributes) as [String : AnyObject] data.updatedAttributes = [String](object.changedValues().keys) metaLogEntry.updateData = data // // Increment the sequence for this record // sequenceNumber += 1 logTrace(4) { "Log entry created: \(metaLogEntry)" } } } fileprivate func logDeleteEntries(_ deletedRecords: Set<NSManagedObject>, transactionID: TransactionID, metadataContext: NSManagedObjectContext, sequenceNumber: inout Int) { for object in deletedRecords { let metaLogEntry = self.transactionLogEntry(MetaLogEntryType.delete, object: object, transactionID: transactionID, metadataContext: metadataContext, sequenceNumber: sequenceNumber) // // Increment the sequence for this record // sequenceNumber += 1 logTrace(4) { "Log entry created: \(metaLogEntry)" } } } fileprivate func transactionLogEntry(_ type: MetaLogEntryType, object: NSManagedObject, transactionID: TransactionID, metadataContext: NSManagedObjectContext, sequenceNumber: Int) -> MetaLogEntry { let metaLogEntry = NSEntityDescription.insertNewObject(forEntityName: MetaLogEntryName, into: metadataContext) as! MetaLogEntry metaLogEntry.transactionID = transactionID metaLogEntry.sequenceNumber = Int32(sequenceNumber) metaLogEntry.previousSequenceNumber = Int32(sequenceNumber - 1) metaLogEntry.type = MetaLogEntryType.endMarker metaLogEntry.timestamp = Date().timeIntervalSinceNow // // Update the object identification data // metaLogEntry.updateObjectID = object.objectID.uriRepresentation().absoluteString metaLogEntry.updateEntityName = object.entity.name return metaLogEntry } } <file_sep>/// /// CoreDataStackTests.swift /// /// Copyright 2016 The Climate Corporation /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 1/15/16. /// import XCTest import CoreData import Coherence fileprivate let firstName = "First" fileprivate let lastName = "Last" fileprivate let userName = "<NAME>" class CoreDataStackTests: XCTestCase { override func setUp() { super.setUp() do { try removePersistentStoreCache() } catch { XCTFail(error.localizedDescription) } } override func tearDown() { do { try removePersistentStoreCache() } catch { XCTFail(error.localizedDescription) } super.tearDown() } func testConstruction () { let storePrefix = String(describing: TestModel1.self) do { let _ = try CoreDataStack(managedObjectModel: TestModel1(), storeNamePrefix: storePrefix) XCTAssertTrue(try persistentStoreExists(storePrefix: storePrefix, storeType: defaultStoreType)) } catch { XCTFail(error.localizedDescription) } } func testConstruction_WithOptions () { let storePrefix = String(describing: TestModel1.self) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true do { let _ = try CoreDataStack(managedObjectModel: TestModel1(), storeNamePrefix: storePrefix, configurationOptions: [defaultModelConfigurationName: (storeType: NSSQLiteStoreType, storeOptions: options, migrationManager: nil)]) XCTAssertTrue(try persistentStoreExists(storePrefix: storePrefix, storeType: defaultStoreType)) } catch { XCTFail(error.localizedDescription) } } func testCRUD () throws { let coreDataStack = try CoreDataStack(managedObjectModel: TestModel1(), storeNamePrefix: String(describing: TestModel1.self)) let editContext = coreDataStack.editContext() let mainThreadContext = coreDataStack.mainThreadContext() var userId: NSManagedObjectID? = nil editContext.performAndWait { if let insertedUser = NSEntityDescription.insertNewObject(forEntityName: "User", into:editContext) as? User { insertedUser.firstName = firstName insertedUser.lastName = lastName insertedUser.userName = userName do { try editContext.save() } catch { XCTFail() } userId = insertedUser.objectID } } var savedUser: NSManagedObject? = nil mainThreadContext.performAndWait { if let userId = userId { savedUser = mainThreadContext.object(with: userId) } } XCTAssertNotNil(savedUser) if let savedUser = savedUser as? User { XCTAssertTrue(savedUser.firstName == firstName) XCTAssertTrue(savedUser.lastName == lastName) XCTAssertTrue(savedUser.userName == userName) } else { XCTFail() } } fileprivate func deleteIfExists(fileURL url: URL) throws { let fileManager = FileManager.default let path = url.path if fileManager.fileExists(atPath: path) { try fileManager.removeItem(at: url) } } } <file_sep>/// /// ConfigurationTests.swift /// /// Copyright 2016 The Climate Corporation /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 6/22/15. /// import XCTest import Coherence typealias Char = Int8 let charPListTestValue: Character = "A" let boolPListTestValue: Bool = true let integerPListTestValue: Int = 12345 let unsignedIntegerPListTestValue: UInt = 12345 let floatPListTestValue: Float = 12345.67 let doublePListTestValue: Double = 12345.67 let stringPListTestValue: String = "String test value" let charTestValue: Character = "b" let boolTestValue: Bool = true let integerTestValue: Int = 54321 let unsignedIntegerTestValue: UInt = 54321 let floatTestValue: Float = 54321.67 let doubleTestValue: Double = 54321.67 let stringTestValue: String = "String test value 2" let stringReadonlyTestValue: String = "Readonly string test value" let intReadonlyTestValue: Int = 1 // // Test configuration when developers are using a pure protocol // for their configuration construction. // @objc internal protocol TestPureProtocolConfiguration : NSObjectProtocol { // var charProperty: Character { get set } var boolProperty: Bool { get set } var integerProperty: Int { get set } var unsignedIntegerProperty: UInt { get set } var floatProperty: Float { get set } var doubleProperty: Double { get set } var stringProperty: String {get set } } // // Test configuration when developers are using a subclass // of CCConfiguration for their configuration using default values. @objc internal protocol TestSubClassConfiguration : NSObjectProtocol { // var charProperty: Character { get set } var boolProperty: Bool { get set } var integerProperty: Int { get set } var unsignedIntegerProperty: UInt { get set } var floatProperty: Float { get set } var doubleProperty: Double { get set } var stringProperty: String {get set } var stringPropertyReadonly: String { get } var intPropertyReadonly: Int { get } } class TestSubClassConfigurationClass : Configuration<TestSubClassConfiguration> { override class func defaults () -> [String : AnyObject] { return ["stringPropertyReadonly" : stringReadonlyTestValue as AnyObject, "intPropertyReadonly": intReadonlyTestValue as AnyObject] } } class ConfigurationTests : XCTestCase { func testPureProtocolConfigurationConstruction () { XCTAssertNotNil(Configuration<TestPureProtocolConfiguration>.instance()) } func testPureProtocolConfigurationCRUD () { let configuration = Configuration<TestPureProtocolConfiguration>.instance() // Note all values are filled with the values from the info.plist // XCTAssertEqual (configuration.charProperty, charPListTestValue) XCTAssertEqual (configuration.boolProperty, boolPListTestValue) XCTAssertEqual (configuration.integerProperty, integerPListTestValue) XCTAssertEqual (configuration.unsignedIntegerProperty, unsignedIntegerPListTestValue) XCTAssertEqual (configuration.floatProperty, floatPListTestValue) XCTAssertEqual (configuration.doubleProperty, doublePListTestValue) XCTAssertEqual (configuration.stringProperty, stringPListTestValue) } func testSubclassConfigurationConstruction () { XCTAssertNotNil(TestSubClassConfigurationClass.instance()) } func testSubclassConfigurationCRUD () { let configuration: TestSubClassConfiguration = TestSubClassConfigurationClass.instance() // Note all values are filled with the values from the info.plist // XCTAssertEqual (configuration.charProperty, charPListTestValue) XCTAssertEqual (configuration.boolProperty, boolPListTestValue) XCTAssertEqual (configuration.integerProperty, integerPListTestValue) XCTAssertEqual (configuration.unsignedIntegerProperty, unsignedIntegerPListTestValue) XCTAssertEqual (configuration.floatProperty, floatPListTestValue) XCTAssertEqual (configuration.doubleProperty, doublePListTestValue) XCTAssertEqual (configuration.stringProperty, stringPListTestValue) XCTAssertEqual (configuration.stringPropertyReadonly, stringReadonlyTestValue) XCTAssertEqual (configuration.intPropertyReadonly, intReadonlyTestValue) } } <file_sep>/// /// GenericCoreDataStackTests.swift /// /// Copyright 2016 The Climate Corporation /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 10/31/16. /// import XCTest import CoreData import Coherence fileprivate let firstName = "First" fileprivate let lastName = "Last" fileprivate let userName = "<NAME>" class GenericCoreDataStackTests: XCTestCase { fileprivate typealias CoreDataStackType = GenericCoreDataStack<NSPersistentStoreCoordinator, NSManagedObjectContext> override func setUp() { super.setUp() do { try removePersistentStoreCache() } catch { XCTFail(error.localizedDescription) } } override func tearDown() { do { try removePersistentStoreCache() } catch { XCTFail(error.localizedDescription) } super.tearDown() } func testConstruction() { let model = TestModel1() let prefix = String(describing: type(of: model.self)) do { let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType)) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_WithOptions() { let model = TestModel1() let prefix = String(describing: type(of: model.self)) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true do { let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: [defaultModelConfigurationName: (storeType: NSSQLiteStoreType, storeOptions: options, migrationManager: nil)]) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType)) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_WithEmptyOptions() { let model = TestModel1() let prefix = String(describing: type(of: model.self)) do { let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: [:]) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType)) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_MultiConfiguration_SQLiteStoreType() throws { let model = TestModel3() let prefix = String(describing: type(of: model.self)) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true do { /// TestModel2 has multiple configurations and should will produce multiple persistent stores. let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: ["PersistentEntities": (storeType: NSSQLiteStoreType, storeOptions: options, migrationManager: nil), "TransientEntities": (storeType: NSSQLiteStoreType, storeOptions: options, migrationManager: nil)]) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: NSSQLiteStoreType, configuration: "PersistentEntities")) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: NSSQLiteStoreType, configuration: "TransientEntities")) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_MultiConfiguration_InMemoryType() throws { let model = TestModel3() let prefix = String(describing: type(of: model.self)) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true do { /// TestModel2 has multiple configurations and should will produce multiple persistent stores. let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: ["PersistentEntities": (storeType: NSInMemoryStoreType, storeOptions: options, migrationManager: nil), "TransientEntities": (storeType: NSInMemoryStoreType, storeOptions: options, migrationManager: nil)]) XCTAssertFalse(try persistentStoreExists(storePrefix: prefix, storeType: NSInMemoryStoreType, configuration: "PersistentEntities")) XCTAssertFalse(try persistentStoreExists(storePrefix: prefix, storeType: NSInMemoryStoreType, configuration: "TransientEntities")) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_MultiConfiguration_MixedType() throws { let model = TestModel3() let prefix = String(describing: type(of: model.self)) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true do { /// TestModel2 has multiple configurations and should will produce multiple persistent stores. let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: ["PersistentEntities": (storeType: NSSQLiteStoreType, storeOptions: options, migrationManager: nil), "TransientEntities": (storeType: NSInMemoryStoreType, storeOptions: options, migrationManager: nil)]) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: NSSQLiteStoreType, configuration: "PersistentEntities")) XCTAssertFalse(try persistentStoreExists(storePrefix: prefix, storeType: NSInMemoryStoreType, configuration: "TransientEntities")) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testConstruction_MultiConfiguration_DefaultStoreType() throws { let model = TestModel3() let prefix = String(describing: type(of: model.self)) do { /// TestModel2 has multiple configurations and should will produce multiple persistent stores. let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType, configuration: "PersistentEntities")) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType, configuration: "TransientEntities")) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testStackCreation_OverrideStoreIfModelIncompatible() throws { let model = TestModel1() let prefix = String(describing: type(of: model.self)) let storeType = NSSQLiteStoreType do { // Initialize model 2 (no configurations), with model 1s name let _ = try CoreDataStackType(managedObjectModel: TestModel2(), storeNamePrefix: prefix) } let storeDate = try persistentStoreDate(storePrefix: prefix, storeType: storeType, configuration: nil) sleep(2) var options: [AnyHashable: Any] = defaultStoreOptions options[overwriteIncompatibleStoreOption] = true // Now use model 1 with model 1s name let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: [defaultModelConfigurationName: (storeType: storeType, storeOptions: options, migrationManager: nil)]) XCTAssertTrue(try persistentStoreDate(storePrefix: prefix, storeType: storeType, configuration: nil) > storeDate) } func testStackCreation_ForceIncompatibleStore() throws { let model = TestModel1() let prefix = String(describing: type(of: model.self)) let storeType = NSSQLiteStoreType // Initialize model 2 (no configurations), with model 1s name let stack = try CoreDataStackType(managedObjectModel: TestModel2(), storeNamePrefix: prefix) // Now use model 1 with model 1s name XCTAssertThrowsError(try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, configurationOptions: [defaultModelConfigurationName: (storeType: storeType, storeOptions: [:], migrationManager: nil)])) // Cleanup after stack. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } func testConstruction_WithAsyncErrorHandler() { let model = TestModel1() let prefix = String(describing: type(of: model.self)) do { let stack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix, asyncErrorBlock: { (error) -> Void in // Async Error block print(error.localizedDescription) }) XCTAssertTrue(try persistentStoreExists(storePrefix: prefix, storeType: defaultStoreType)) // Cleanup after test. try stack.persistentStoreCoordinator.persistentStores.forEach { (store) throws in try stack.persistentStoreCoordinator.remove(store) } } catch { XCTFail(error.localizedDescription) } } func testCRUD () throws { let model = TestModel1() let prefix = String(describing: type(of: model.self)) let coreDataStack = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: prefix) let editContext = coreDataStack.editContext() let mainThreadContext = coreDataStack.mainThreadContext() var userId: NSManagedObjectID? = nil editContext.performAndWait { if let insertedUser = NSEntityDescription.insertNewObject(forEntityName: "User", into:editContext) as? User { insertedUser.firstName = firstName insertedUser.lastName = lastName insertedUser.userName = userName do { try editContext.save() } catch { XCTFail() } userId = insertedUser.objectID } } var savedUser: NSManagedObject? = nil mainThreadContext.performAndWait { if let userId = userId { savedUser = mainThreadContext.object(with: userId) } } XCTAssertNotNil(savedUser) if let savedUser = savedUser as? User { XCTAssertTrue(savedUser.firstName == firstName) XCTAssertTrue(savedUser.lastName == lastName) XCTAssertTrue(savedUser.userName == userName) } else { XCTFail() } } } <file_sep># Coherence ![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-lightgray.svg?style=flat) <a href="https://github.com/tonystone/coherence/" target="_blank"> <img src="https://img.shields.io/badge/Platforms-ios%20%7C%20osx-lightgray.svg?style=flat" alt="Platforms: ios | osx"> </a> <a href="https://github.com/tonystone/coherence/" target="_blank"> <img src="https://img.shields.io/cocoapods/v/Coherence.svg?style=flat" alt="Pod version"> </a> <a href="https://github.com/tonystone/coherence/" target="_blank"> <img src="https://img.shields.io/badge/Swift-4.1-orange.svg?style=flat" alt="Swift 4.1"> </a> [![Build Status](https://travis-ci.org/tonystone/coherence.svg?branch=master)](https://travis-ci.org/tonystone/coherence) <a href="https://codecov.io/gh/tonystone/coherence">   <img src="https://codecov.io/gh/tonystone/coherence/branch/master/graph/badge.svg" alt="Codecov" /> </a> ## Requirements | Xcode | Swift | iOS | |:-----:|:-----:|:---:| | 9.4 | 4.1 | 8.0 | ## Author <NAME> ([https://github.com/tonystone] (https://github.com/tonystone)) ## License Coherence is released under the [Apache License, Version 2.0] (http://www.apache.org/licenses/LICENSE-2.0.html) <file_sep>/** * MetaModel.swift * * Copyright 2015 <NAME> * * 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. * * Created by <NAME> on 12/10/15. */ import Foundation import CoreData internal class MetaModel: NSManagedObjectModel { override init() { super.init() self.entities = [self.metaLogEntry(), self.refreshStatus()] self.versionIdentifiers = [1] } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func metaLogEntry() -> NSEntityDescription { var attributes = [NSAttributeDescription]() let sequenceNumber = NSAttributeDescription() sequenceNumber.name = "sequenceNumber" sequenceNumber.isOptional = false sequenceNumber.attributeType = NSAttributeType.integer32AttributeType attributes.append(sequenceNumber) let previousSequenceNumber = NSAttributeDescription() previousSequenceNumber.name = "previousSequenceNumber" previousSequenceNumber.isOptional = false previousSequenceNumber.attributeType = NSAttributeType.integer32AttributeType attributes.append(previousSequenceNumber) let transactionID = NSAttributeDescription() transactionID.name = "transactionID" transactionID.isOptional = false transactionID.attributeType = NSAttributeType.stringAttributeType attributes.append(transactionID) let timestamp = NSAttributeDescription() timestamp.name = "timestamp" timestamp.isOptional = false timestamp.attributeType = NSAttributeType.dateAttributeType attributes.append(timestamp) let type = NSAttributeDescription() type.name = "type" type.isOptional = false type.attributeType = NSAttributeType.integer32AttributeType attributes.append(type) let updateEntityName = NSAttributeDescription() updateEntityName.name = "updateEntityName" updateEntityName.isOptional = true updateEntityName.attributeType = NSAttributeType.stringAttributeType attributes.append(updateEntityName) let updateObjectID = NSAttributeDescription() updateObjectID.name = "updateObjectID" updateObjectID.isOptional = true updateObjectID.attributeType = NSAttributeType.stringAttributeType attributes.append(updateObjectID) let updateUniqueID = NSAttributeDescription() updateUniqueID.name = "updateUniqueID" updateUniqueID.isOptional = true updateUniqueID.attributeType = NSAttributeType.stringAttributeType attributes.append(updateUniqueID) let updateData = NSAttributeDescription() updateData.name = "updateData" updateData.isOptional = true updateData.attributeType = NSAttributeType.transformableAttributeType attributes.append(updateData) let entity = NSEntityDescription() entity.name = "MetaLogEntry" entity.managedObjectClassName = "MetaLogEntry" entity.properties = attributes return entity; } fileprivate func refreshStatus() -> NSEntityDescription { var attributes = [NSAttributeDescription]() let name = NSAttributeDescription() name.name = "name" name.isOptional = false name.attributeType = NSAttributeType.stringAttributeType attributes.append(name) let type = NSAttributeDescription() type.name = "type" type.isOptional = false type.attributeType = NSAttributeType.stringAttributeType // type.defaultValue = kDefaultRefreshType attributes.append(type) let scope = NSAttributeDescription() scope.name = "scope" scope.isOptional = true scope.attributeType = NSAttributeType.stringAttributeType scope.isIndexed = true attributes.append(scope) let lastSyncError = NSAttributeDescription() lastSyncError.name = "lastSyncError" lastSyncError.isOptional = true lastSyncError.attributeType = NSAttributeType.transformableAttributeType attributes.append(lastSyncError) let lastSyncStatus = NSAttributeDescription() lastSyncStatus.name = "lastSyncStatus" lastSyncStatus.isOptional = true lastSyncStatus.attributeType = NSAttributeType.integer32AttributeType attributes.append(lastSyncStatus) let lastSyncTime = NSAttributeDescription() lastSyncTime.name = "lastSyncTime" lastSyncTime.isOptional = true lastSyncTime.attributeType = NSAttributeType.dateAttributeType attributes.append(lastSyncTime) let entity = NSEntityDescription() entity.name = "RefreshStatus" entity.managedObjectClassName = "RefreshStatus" entity.properties = attributes return entity; } } <file_sep>/// /// GenericCoreDataStack.swift /// /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 1/6/16. /// import Foundation import CoreData import TraceLog /** The name of the default configuration in the model. If you have not created any configurations, this will be the only configuration avaialble. Use this name if you override the options passed. */ public let defaultModelConfigurationName: String = "PF_DEFAULT_CONFIGURATION_NAME" /** An option – when set to true – will check if the persistent store and the model are incompatible. If so, the underlying persistent store will be removed and replaced. */ public let overwriteIncompatibleStoreOption: String = "overwriteIncompatibleStoreOption" /** Default options passed to attached and configure the persistent stores. */ public let defaultStoreOptions: [AnyHashable: Any] = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] /** If no storeType is passed in, this store type will be used */ public let defaultStoreType = NSSQLiteStoreType /** PersistentStore configuration settings. */ public typealias PersistentStoreConfiguration = (storeType: String, storeOptions: [AnyHashable: Any]?, migrationManager: NSMigrationManager?) /** Configuration options dictionary keyed by configuration name. The name is the name you listed in your model. */ public typealias ConfigurationOptionsType = [String : PersistentStoreConfiguration] /** The detault configuration options used to configure the persistent store when no override is supplied. */ public let defaultConfigurationOptions: ConfigurationOptionsType = [defaultModelConfigurationName : (storeType: defaultStoreType, storeOptions: defaultStoreOptions, migrationManager: nil)] /** There are activities that the CoreDataStack will do asyncrhonously as a result of various events. GenericCoreDataStack currently logs those events, if you would like to handle them yourself, you can set an error block which will be called to allow you to take an alternate action. */ public typealias asynErrorHandlerBlock = (NSError) -> Void /** A Core Data stack that can be customized with specific NSPersistentStoreCoordinator and a NSManagedObjectContext Context type. */ open class GenericCoreDataStack<CoordinatorType: NSPersistentStoreCoordinator, ContextType: NSManagedObjectContext> { /// /// The model this `GenericCoreDataStack` was constructed with. /// public let managedObjectModel: NSManagedObjectModel /// /// Returns the `NSPersistentStoreCoordinate` instance that /// this `GenericCoreDataStack` contains. It's type will /// be `CoordinatorType` which was given as a generic /// parameter during construction. /// public let persistentStoreCoordinator: CoordinatorType fileprivate let tag: String fileprivate let mainContext: ContextType fileprivate let errorHandlerBlock: (_ error: NSError) -> Void /** Initializes the receiver with a managed object model. - parameters: - managedObjectModel: A managed object model. - configurationOptions: Optional configuration settings by persistent store config name (see ConfigurationOptionsType for structure) - storeNamePrefix: An optional String which is appended to the beginning of the persistent store's name. - logTag: An optional String that will be used as the tag for logging (default is GenericCoreDataStack). This is typically used if you are embedding GenericCoreDataStack in something else and you want to to log as your class. */ public init(managedObjectModel model: NSManagedObjectModel, storeNamePrefix: String, configurationOptions options: ConfigurationOptionsType = defaultConfigurationOptions, asyncErrorBlock: ((_ error: NSError) -> Void)? = nil, logTag tag: String = String(describing: GenericCoreDataStack.self)) throws { self.managedObjectModel = model self.tag = tag if let asyncErrorBlock = asyncErrorBlock { self.errorHandlerBlock = asyncErrorBlock } else { self.errorHandlerBlock = { (error: NSError) -> Void in logError { error.localizedDescription } } } // Create the coordinator persistentStoreCoordinator = CoordinatorType(managedObjectModel: managedObjectModel) // Now the main thread context mainContext = ContextType(concurrencyType: .mainQueueConcurrencyType) mainContext.persistentStoreCoordinator = self.persistentStoreCoordinator // // Figure out where to put things // // Note: We use the applications bundle not the classes or modules. // let cachesURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) logInfo(tag) { "Store path: \(cachesURL.path)" } let configurations = managedObjectModel.configurations // There is only one so it's the default configuration if configurations.count == 1 { if let (storeType, storeOptions, migrationManager) = options[defaultModelConfigurationName] { let storeURL = cachesURL.appendingPathComponent("\(storeNamePrefix).\(storeType)") try self.addPersistentStore(storeType, configuration: nil, URL: storeURL, options: storeOptions, migrationManger: migrationManager) } else { let storeURL = cachesURL.appendingPathComponent("\(storeNamePrefix).\(defaultStoreType)") try self.addPersistentStore(defaultStoreType, configuration: nil, URL: storeURL, options: nil, migrationManger: nil) } } else { for configuration in configurations { if configuration != defaultModelConfigurationName { if let (storeType, storeOptions, migrationManager) = options[configuration] { let storeURL = cachesURL.appendingPathComponent("\(storeNamePrefix)\(configuration).\(storeType)") try self.addPersistentStore(storeType, configuration: configuration, URL: storeURL, options: storeOptions, migrationManger: migrationManager) } else { let storeURL = cachesURL.appendingPathComponent("\(storeNamePrefix)\(configuration).\(defaultStoreType)") try self.addPersistentStore(defaultStoreType, configuration: configuration, URL: storeURL, options: nil, migrationManger: nil) } } } } NotificationCenter.default.addObserver(self, selector: #selector(GenericCoreDataStack.handleContextDidSaveNotification(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } open func mainThreadContext () -> NSManagedObjectContext { return mainContext } open func editContext () -> NSManagedObjectContext { logInfo(tag) { "Creating edit context for \(Thread.current)..." } let context = ContextType(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) context.parent = mainContext logInfo(tag) { "Edit context created." } return context } fileprivate func addPersistentStore(_ storeType: String, configuration: String?, URL storeURL: URL, options: [AnyHashable: Any]?, migrationManger migrator: NSMigrationManager?) throws { do { // // If a migration manager was supplied, try a migration first. // if let migrationManager = migrator { if let mappingModel = NSMappingModel(from: nil, forSourceModel: migrationManager.sourceModel, destinationModel: migrationManager.destinationModel) { // TODO: Rename old file first try migrationManager.migrateStore(from: storeURL, sourceType: storeType, options: options, with: mappingModel, toDestinationURL: storeURL, destinationType: storeType, destinationOptions: options) } } logInfo(tag) { "Attaching persistent store \"\(storeURL.lastPathComponent)\" for type: \(storeType)."} let fileManager = FileManager.default let storePath = storeURL.path if fileManager.fileExists(atPath: storePath) { let storeShmPath = "\(storePath)-shm" let storeWalPath = "\(storePath)-wal" // Check the store for compatibility if requested by developer. if options?[overwriteIncompatibleStoreOption] as? Bool == true { logInfo(tag) { "Checking to see if persistent store is compatible with the model." } let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: storeType, at: storeURL, options: nil) if !persistentStoreCoordinator.managedObjectModel.isConfiguration(withName: configuration, compatibleWithStoreMetadata: metadata) { logInfo { "Store not compatible with metadata, removing stores..." } try deleteIfExists(storePath) try deleteIfExists(storeShmPath) try deleteIfExists(storeWalPath) } } } logInfo(tag) { "Attaching new persistent store \"\(storeURL.lastPathComponent)\" for type: \(storeType)."} try persistentStoreCoordinator.addPersistentStore(ofType: storeType, configurationName: configuration, at: storeURL, options: options) logInfo(tag) { "Persistent store attached successfully." } } catch let error as NSError where [NSMigrationError, NSMigrationConstraintViolationError, NSMigrationCancelledError, NSMigrationMissingSourceModelError, NSMigrationMissingMappingModelError, NSMigrationManagerSourceStoreError, NSMigrationManagerDestinationStoreError].contains(error.code) { let message = "Migration failed due to error: \(error.localizedDescription)" logError { message } var userInfo: [AnyHashable: Any] = error.userInfo userInfo[NSLocalizedDescriptionKey] = message throw NSError(domain: error.domain, code: error.code, userInfo: userInfo as? [String : Any]) } catch let error as NSError { let message = "Failed to attached persistent store: \(error.localizedDescription)" logError { message } var userInfo: [AnyHashable: Any] = error.userInfo userInfo[NSLocalizedDescriptionKey] = message throw NSError(domain: error.domain, code: error.code, userInfo: userInfo as? [String : Any]) } } fileprivate func deleteIfExists(_ path: String) throws { let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { logInfo(tag) { "Removing file \(path)." } try fileManager.removeItem(atPath: path) } } @objc fileprivate dynamic func handleContextDidSaveNotification(_ notification: Notification) { if let context = notification.object as? NSManagedObjectContext { // // If the saved context has it's parent set to our // mainThreadContext auto save the main context // if context.parent == mainContext { mainContext.perform( { () -> Void in do { try self.mainContext.save() } catch let error as NSError { self.errorHandlerBlock(error) } }) } } } } <file_sep>/// /// CoreDataStack.swift /// /// Copyright 2016 <NAME> /// /// 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. /// /// Created by <NAME> on 12/14/15. /// import Foundation import CoreData import TraceLog @objc public final class CoreDataStack: NSObject { fileprivate typealias CoreDataStackType = GenericCoreDataStack<NSPersistentStoreCoordinator, NSManagedObjectContext> fileprivate let impl: CoreDataStackType /** Initializes the receiver with a managed object model. - parameters: - managedObjectModel: A managed object model. - storeNamePrefix: A unique name prefix for the persistent store to be created. */ @objc public init(managedObjectModel model: NSManagedObjectModel, storeNamePrefix: String) throws { impl = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: storeNamePrefix, logTag: String(describing: CoreDataStack.self)) } /** Initializes the receiver with a managed object model. - parameters: - managedObjectModel: A managed object model. - storeNamePrefix: A unique name prefix for the persistent store to be created. - configurationOptions: Optional configuration settings by persistent store config name (see ConfigurationOptionsType for structure) */ public init(managedObjectModel model: NSManagedObjectModel, storeNamePrefix: String, configurationOptions options: ConfigurationOptionsType) throws { impl = try CoreDataStackType(managedObjectModel: model, storeNamePrefix: storeNamePrefix, configurationOptions: options, logTag: String(describing: CoreDataStack.self)) } @objc public func mainThreadContext () -> NSManagedObjectContext { return impl.mainThreadContext() } @objc public func editContext () -> NSManagedObjectContext { return impl.editContext() } }
efb89c28922042f1e05f0ca2593099bde338d528
[ "Swift", "C", "Ruby", "Markdown" ]
20
Swift
TheClimateCorporation/coherence-2-x-swift-4
5d48a3eba894f30cd005f160c0328fb9ddb966f4
2f7a7bcc31600501540b3e74bdea99d6eb14bd13
refs/heads/master
<file_sep>module RecipesHelper def filter_heading(search_term) day = Date.today.strftime("%A") if @search_term == "" "#{day} is a great day for " else "You searched for #{search_term}." end end def filter_string(ranking) ranking = ranking.round(1) end def pagination_next number_next = @search_page.to_i + 1 number_next.to_s end def pagination_prev number_prev = @search_page.to_i - 1 number_prev.to_s end end <file_sep>class RecipesController < ApplicationController def index @search_term = params[:search] || '' @search_sort = params[:sort] || '' @search_page = params[:page] || 1 @recipes = Recipe.for(@search_term, @search_sort, @search_page) end end<file_sep>== README This project is a modified version of an assignment for Ruby on Rails: An Introduction, first part of Ruby on Rails Web Development Specialization (Coursera | Johns Hopkins University | October 2015) Besides the requirements for the assignment, it * implements search box * implements links to previous and next pages * implements sorting by rating and trending (note: the API only allows sorting *before* searching, the same behavior happens on Food2Fork website) * has modified HTML structure (from table to columns) * uses Twitter Bootstrap framework * implements helpers and partial views<file_sep>module ApplicationHelper def shorten_name(string) if string.length > 25 "#{string[0...20]}..." else string end end end
d7f30fa5c7c980fbc99b3248bb7770c93eb19cdd
[ "RDoc", "Ruby" ]
4
Ruby
pwdd/recipe_finder
b986b9f8210db6b6dbca205e78b9a91fda914119
6fd0966a3f79dbe499b141fdbcd3057f0516a9e9
refs/heads/master
<repo_name>volente/manesapo<file_sep>/settings.gradle rootProject.name = 'manesapo' <file_sep>/src/test/java/com/rocksbook/manesapo/ManesapoApplicationTests.java package com.rocksbook.manesapo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ManesapoApplicationTests { @Test void contextLoads() { } }
b0c089e82709e5483cfe1906fc920a635a468429
[ "Java", "Gradle" ]
2
Gradle
volente/manesapo
362318d2f96349df72a4e4c64c947d22684aefe8
364092a37b3e327934c926098dac9b7bdc439548
refs/heads/master
<file_sep>import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText #mime(物件)包下常用的三個模組: text image(圖像) multipart。text常用於製作文字內文 gmail_user='<EMAIL>' gmail_password='<PASSWORD>' from_address=gmail_user to_address=['<EMAIL>'] Subject="Hi" contents="ergrgrttg" mail =MIMEMultipart() mail['From'] =from_address mail['To']=','.join(to_address)#指定寄件人的清單 mail['Subject']=Subject mail.attach(MIMEText(contents))#內文附加在信件中 smtpserver= smtplib.SMTP_SSL("smtp.gmail.com",465)#安全傳輸層通訊附 smtpserver.ehlo() smtpserver.login(gmail_user,gmail_password) smtpserver.sendmail(from_address,to_address,mail.as_string())#寄件者的地址,收件者的地址都變成字串 smtpserver.quit() <file_sep>"# auto-mail" "# auto-mail"
9a4c2ad4d3ad2dc957c603695b27c430da45eebd
[ "Markdown", "Python" ]
2
Python
Timothy12christ/mail
994058b678f59845bbfbf7d7dac54debced589c4
1d5d0ac9d7f95aea3f4559606476e427c7552ba1
refs/heads/master
<repo_name>Gortubia/solemne3.tiwebcom<file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Provincias_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Provincias.class) public class Provincias_ { public static volatile SingularAttribute<Provincias, Integer> regionId; public static volatile SingularAttribute<Provincias, Integer> provinciaId; public static volatile SingularAttribute<Provincias, String> provinciaNombre; }<file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/presentacion/ValidaUsuarioServlet.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.presentacion; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Usuario; import cl.duoc.dej4501.solemne3.tiwebcom.persistence.UsuarioSessionBean; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author adolf */ @WebServlet(name = "ValidaUsuarioServlet", urlPatterns = {"/validaUsuarioServlet"}) public class ValidaUsuarioServlet extends HttpServlet { @EJB private UsuarioSessionBean usuarioSB; // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession sesion = request.getSession(); String login = request.getParameter("txtLogin"); String pass = request.getParameter("txtPass"); Usuario usuarioConectado = usuarioSB.buscaUsuario(login, pass); if (usuarioConectado != null) { sesion.setAttribute("usuarioConectado", usuarioConectado); response.sendRedirect("home.jsp"); } else { sesion.setAttribute("msgError", "Usuario No Existe"); response.sendRedirect("login.jsp"); } } } <file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Cliente_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Boleta; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Perfil; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Usuario_1; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Cliente.class) public class Cliente_ { public static volatile SingularAttribute<Cliente, String> rut; public static volatile SingularAttribute<Cliente, Integer> idCliente; public static volatile SingularAttribute<Cliente, Perfil> idPerfil; public static volatile SingularAttribute<Cliente, Usuario_1> idUsuario; public static volatile SingularAttribute<Cliente, String> direccion; public static volatile ListAttribute<Cliente, Boleta> boletaList; }<file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Usuario_1_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Cliente; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Usuario_1.class) public class Usuario_1_ { public static volatile ListAttribute<Usuario_1, Cliente> clienteList; public static volatile SingularAttribute<Usuario_1, String> apellidoUsuario; public static volatile SingularAttribute<Usuario_1, String> correoUsuario; public static volatile SingularAttribute<Usuario_1, Integer> codigoPerfil; public static volatile SingularAttribute<Usuario_1, Integer> idUsuario; public static volatile SingularAttribute<Usuario_1, String> passUsuario; public static volatile SingularAttribute<Usuario_1, String> nombreUsuario; public static volatile SingularAttribute<Usuario_1, String> loginUsuario; public static volatile SingularAttribute<Usuario_1, Date> fechaNacimientousuario; }<file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/persistence/UsuarioSessionBean.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.persistence; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Usuario; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author adolf */ @Stateless public class UsuarioSessionBean { @PersistenceContext private EntityManager em; public List<Usuario> getAllUsuarios(){ return em.createNamedQuery("Usuario.findAll",Usuario.class) .getResultList(); } public Usuario getUsuarioById(int id){ return em.find(Usuario.class, id ); } public Usuario buscaUsuario (String loginUsuario, String passUsuario){ Usuario usuario = null; try { List<Usuario> listausuario = em.createNamedQuery("Usuario.validador", Usuario.class) .setParameter("loginUsuario", loginUsuario) .setParameter("passUsuario", <PASSWORD>) .getResultList(); if(!listausuario.isEmpty()){ usuario = listausuario.get(0); } } catch (Exception e) { } return usuario; } public boolean findByLoginUsuario(String loginUsuario){ boolean usLogin = false; try { List<Usuario> listausuario = em.createNamedQuery("Usuario.findByLoginUsuario", Usuario.class) .setParameter("loginUsuario", loginUsuario) .getResultList(); if(!listausuario.isEmpty()){ usLogin = true; } } catch (Exception e) { } return usLogin; } public int findmaXiD (){ int maxId = 0; try { maxId = (int) em.createQuery("SELECT MAX(u.idUsuario) FROM Usuario u") .getSingleResult(); } catch (Exception e) { } return maxId; } public void guardarUsuario (Usuario us) throws ControllerException{ em.persist(us); } } <file_sep>/nbproject/private/private.properties j2ee.server.domain=C:/DominioOracle j2ee.server.home=C:/fmw_12.2.1.3.0_wls_quick_Disk1_1of1/wls12213/wlserver j2ee.server.instance=deployer:WebLogic:http://localhost:7001:C:\\fmw_12.2.1.3.0_wls_quick_Disk1_1of1\\wls12213\\wlserver:C:\\DominioOracle j2ee.server.middleware=C:/fmw_12.2.1.3.0_wls_quick_Disk1_1of1/wls12213 javac.debug=true javadoc.preview=true selected.browser=default user.properties.file=C:\\Users\\adolf\\AppData\\Roaming\\NetBeans\\8.2\\build.properties <file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/viewDomain/CarritoCompra.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.viewDomain; import java.util.List; /** * * @author adolf */ public class CarritoCompra { private int totalCarrito; private List<ProductoCarrito> listadoProducosCarrito; public CarritoCompra() { } public CarritoCompra(int totalCarrito, List<ProductoCarrito> listadoProducosCarrito) { this.totalCarrito = totalCarrito; this.listadoProducosCarrito = listadoProducosCarrito; } public int getTotalCarrito() { return totalCarrito; } public void setTotalCarrito(int totalCarrito) { this.totalCarrito = totalCarrito; } public List<ProductoCarrito> getListadoProducosCarrito() { return listadoProducosCarrito; } public void setListadoProducosCarrito(List<ProductoCarrito> listadoProducosCarrito) { this.listadoProducosCarrito = listadoProducosCarrito; } } <file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/persistence/BoletaSessionBean.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.persistence; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Boleta; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author adolf */ @Stateless public class BoletaSessionBean { @PersistenceContext private EntityManager em; public List<Boleta> getAllBoletas(){ return em.createNamedQuery("Boleta.findAll",Boleta.class) .getResultList(); } public Boleta getBoletaById(int id){ return em.find(Boleta.class, id ); } public void guardarBoleta (Boleta boleta) throws ControllerException{ em.persist(boleta); } public int findmaXiD (){ int maxId = 0; try { maxId = (int) em.createQuery("SELECT MAX(b.idBoleta) FROM Boleta b") .getSingleResult(); } catch (Exception e) { } return maxId; } } <file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/entity/Usuario.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author adolf */ @Entity @Table(catalog = "bdtiwebcom", schema = "") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u") , @NamedQuery(name = "Usuario.validador", query = "SELECT u FROM Usuario u WHERE u.loginUsuario = :loginUsuario AND u.passUsuario = :passUsuario") , @NamedQuery(name = "Usuario.findByIdUsuario", query = "SELECT u FROM Usuario u WHERE u.idUsuario = :idUsuario") , @NamedQuery(name = "Usuario.findByLoginUsuario", query = "SELECT u FROM Usuario u WHERE u.loginUsuario = :loginUsuario") , @NamedQuery(name = "Usuario.findByPassUsuario", query = "SELECT u FROM Usuario u WHERE u.passUsuario = :passUsuario") , @NamedQuery(name = "Usuario.findByNombreUsuario", query = "SELECT u FROM Usuario u WHERE u.nombreUsuario = :nombreUsuario") , @NamedQuery(name = "Usuario.findByApellidoUsuario", query = "SELECT u FROM Usuario u WHERE u.apellidoUsuario = :apellidoUsuario") , @NamedQuery(name = "Usuario.findByCorreoUsuario", query = "SELECT u FROM Usuario u WHERE u.correoUsuario = :correoUsuario") , @NamedQuery(name = "Usuario.findByCodigoPerfil", query = "SELECT u FROM Usuario u WHERE u.codigoPerfil = :codigoPerfil") , @NamedQuery(name = "Usuario.findByFechaNacimientousuario", query = "SELECT u FROM Usuario u WHERE u.fechaNacimientousuario = :fechaNacimientousuario") , @NamedQuery(name = "Usuario.findByBorrado", query = "SELECT u FROM Usuario u WHERE u.borrado = :borrado")}) public class Usuario implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id_usuario") private Integer idUsuario; @Size(max = 15) @Column(name = "login_usuario") private String loginUsuario; @Size(max = 10) @Column(name = "pass_usuario") private String passUsuario; @Size(max = 15) @Column(name = "nombre_usuario") private String nombreUsuario; @Size(max = 25) @Column(name = "apellido_usuario") private String apellidoUsuario; @Size(max = 50) @Column(name = "correo_usuario") private String correoUsuario; @Column(name = "codigo_perfil") private Integer codigoPerfil; @Column(name = "fechaNacimiento_usuario") @Temporal(TemporalType.DATE) private Date fechaNacimientousuario; private Integer borrado; @OneToMany(mappedBy = "idUsuario") private List<Cliente> clienteList; public Usuario() { } public Usuario(Integer idUsuario) { this.idUsuario = idUsuario; } public Integer getIdUsuario() { return idUsuario; } public void setIdUsuario(Integer idUsuario) { this.idUsuario = idUsuario; } public String getLoginUsuario() { return loginUsuario; } public void setLoginUsuario(String loginUsuario) { this.loginUsuario = loginUsuario; } public String getPassUsuario() { return passUsuario; } public void setPassUsuario(String passUsuario) { this.passUsuario = passUsuario; } public String getNombreUsuario() { return nombreUsuario; } public void setNombreUsuario(String nombreUsuario) { this.nombreUsuario = nombreUsuario; } public String getApellidoUsuario() { return apellidoUsuario; } public void setApellidoUsuario(String apellidoUsuario) { this.apellidoUsuario = apellidoUsuario; } public String getCorreoUsuario() { return correoUsuario; } public void setCorreoUsuario(String correoUsuario) { this.correoUsuario = correoUsuario; } public Integer getCodigoPerfil() { return codigoPerfil; } public void setCodigoPerfil(Integer codigoPerfil) { this.codigoPerfil = codigoPerfil; } public Date getFechaNacimientousuario() { return fechaNacimientousuario; } public void setFechaNacimientousuario(Date fechaNacimientousuario) { this.fechaNacimientousuario = fechaNacimientousuario; } public Integer getBorrado() { return borrado; } public void setBorrado(Integer borrado) { this.borrado = borrado; } @XmlTransient public List<Cliente> getClienteList() { return clienteList; } public void setClienteList(List<Cliente> clienteList) { this.clienteList = clienteList; } @Override public int hashCode() { int hash = 0; hash += (idUsuario != null ? idUsuario.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Usuario)) { return false; } Usuario other = (Usuario) object; if ((this.idUsuario == null && other.idUsuario != null) || (this.idUsuario != null && !this.idUsuario.equals(other.idUsuario))) { return false; } return true; } @Override public String toString() { return "cl.duoc.dej4501.solemne3.tiwebcom.entity.Usuario[ idUsuario=" + idUsuario + " ]"; } } <file_sep>/README.md # solemne3.tiwebcom Solemne nro 3 DEJ4501 ComicsWeb <NAME> <NAME> <file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/persistence/ClienteSessionBean.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.persistence; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Cliente; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author adolf */ @Stateless public class ClienteSessionBean { @PersistenceContext private EntityManager em; public boolean findByLoginUsuario(String rut){ boolean cli = false; try { List<Cliente> listaCliente = em.createNamedQuery("Usuario.Cliente.findByRut", Cliente.class) .setParameter("rut", rut) .getResultList(); if(!listaCliente.isEmpty()){ cli = true; } } catch (Exception e) { } return cli; } } <file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/persistence/PerfilSessionBean.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.persistence; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Perfil; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author adolf */ @Stateless public class PerfilSessionBean { @PersistenceContext private EntityManager em; public List<Perfil> getAllPerfil(){ return em.createNamedQuery("Perfil.findAll",Perfil.class) .getResultList(); } public Perfil getPerfilById(int id){ return em.find(Perfil.class, id ); } } <file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Menu_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Perfil; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Menu.class) public class Menu_ { public static volatile SingularAttribute<Menu, String> nombreMenu; public static volatile SingularAttribute<Menu, Integer> idMenu; public static volatile SingularAttribute<Menu, Integer> padreMenu; public static volatile SingularAttribute<Menu, String> destinoMenu; public static volatile SingularAttribute<Menu, Perfil> idCodigo; }<file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Boleta_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Cliente; import cl.duoc.dej4501.solemne3.tiwebcom.entity.DetBoleta; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Sucursal; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Boleta.class) public class Boleta_ { public static volatile SingularAttribute<Boleta, Sucursal> idSucursal; public static volatile SingularAttribute<Boleta, Date> fecha; public static volatile SingularAttribute<Boleta, Long> total; public static volatile SingularAttribute<Boleta, Cliente> idCliente; public static volatile ListAttribute<Boleta, DetBoleta> detBoletaList; public static volatile SingularAttribute<Boleta, Integer> idBoleta; }<file_sep>/src/java/cl/duoc/dej4501/solemne3/tiwebcom/entity/DetProducto.java /* * 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. */ package cl.duoc.dej4501.solemne3.tiwebcom.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author adolf */ @Entity @Table(name = "det_producto", catalog = "bdtiwebcom", schema = "") @XmlRootElement @NamedQueries({ @NamedQuery(name = "DetProducto.findAll", query = "SELECT d FROM DetProducto d") , @NamedQuery(name = "DetProducto.findByIdDetProducto", query = "SELECT d FROM DetProducto d WHERE d.idDetProducto = :idDetProducto") , @NamedQuery(name = "DetProducto.findByEditorial", query = "SELECT d FROM DetProducto d WHERE d.editorial = :editorial") , @NamedQuery(name = "DetProducto.findByAutor", query = "SELECT d FROM DetProducto d WHERE d.autor = :autor") , @NamedQuery(name = "DetProducto.findByFechaPublicacion", query = "SELECT d FROM DetProducto d WHERE d.fechaPublicacion = :fechaPublicacion") , @NamedQuery(name = "DetProducto.findByNEdicion", query = "SELECT d FROM DetProducto d WHERE d.nEdicion = :nEdicion") , @NamedQuery(name = "DetProducto.findByPaginas", query = "SELECT d FROM DetProducto d WHERE d.paginas = :paginas") , @NamedQuery(name = "DetProducto.findByBorrado", query = "SELECT d FROM DetProducto d WHERE d.borrado = :borrado")}) public class DetProducto implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id_det_producto") private Integer idDetProducto; @Size(max = 100) private String editorial; @Size(max = 100) private String autor; @Column(name = "fecha_publicacion") @Temporal(TemporalType.DATE) private Date fechaPublicacion; @Column(name = "n_edicion") private Integer nEdicion; private Integer paginas; private Integer borrado; @JoinColumn(name = "id_producto", referencedColumnName = "id") @ManyToOne private Producto idProducto; public DetProducto() { } public DetProducto(Integer idDetProducto) { this.idDetProducto = idDetProducto; } public Integer getIdDetProducto() { return idDetProducto; } public void setIdDetProducto(Integer idDetProducto) { this.idDetProducto = idDetProducto; } public String getEditorial() { return editorial; } public void setEditorial(String editorial) { this.editorial = editorial; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public Date getFechaPublicacion() { return fechaPublicacion; } public void setFechaPublicacion(Date fechaPublicacion) { this.fechaPublicacion = fechaPublicacion; } public Integer getNEdicion() { return nEdicion; } public void setNEdicion(Integer nEdicion) { this.nEdicion = nEdicion; } public Integer getPaginas() { return paginas; } public void setPaginas(Integer paginas) { this.paginas = paginas; } public Integer getBorrado() { return borrado; } public void setBorrado(Integer borrado) { this.borrado = borrado; } public Producto getIdProducto() { return idProducto; } public void setIdProducto(Producto idProducto) { this.idProducto = idProducto; } @Override public int hashCode() { int hash = 0; hash += (idDetProducto != null ? idDetProducto.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DetProducto)) { return false; } DetProducto other = (DetProducto) object; if ((this.idDetProducto == null && other.idDetProducto != null) || (this.idDetProducto != null && !this.idDetProducto.equals(other.idDetProducto))) { return false; } return true; } @Override public String toString() { return "cl.duoc.dej4501.solemne3.tiwebcom.entity.DetProducto[ idDetProducto=" + idDetProducto + " ]"; } } <file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/DetProducto_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import cl.duoc.dej4501.solemne3.tiwebcom.entity.Producto; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(DetProducto.class) public class DetProducto_ { public static volatile SingularAttribute<DetProducto, String> descripcion; public static volatile SingularAttribute<DetProducto, String> detalleProducto; public static volatile SingularAttribute<DetProducto, Integer> idDetProducto; public static volatile SingularAttribute<DetProducto, Producto> idProducto; }<file_sep>/build/generated-sources/ap-source-output/cl/duoc/dej4501/solemne3/tiwebcom/entity/Regiones_.java package cl.duoc.dej4501.solemne3.tiwebcom.entity; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-19T17:01:46") @StaticMetamodel(Regiones.class) public class Regiones_ { public static volatile SingularAttribute<Regiones, String> regionNombre; public static volatile SingularAttribute<Regiones, Integer> regionId; public static volatile SingularAttribute<Regiones, String> regionOrdinal; }
5a62d90711e742e969d86a65468563e24a411d83
[ "Markdown", "Java", "INI" ]
17
Java
Gortubia/solemne3.tiwebcom
b817d11a64ddd0d7f4370ff80b490b0e1b6fbe7e
c2c87c4a8bf6bf8ac1a51dc00499193982c2f41e
refs/heads/main
<file_sep>using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SuperHeroProject.Data; using SuperHeroProject.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SuperHeroProject.Controllers { public class SuperHeroController : Controller { private readonly ApplicationDbContext _context; public SuperHeroController(ApplicationDbContext context) { _context = context; } public IActionResult Index() { var superheroes = _context.SuperHeroes; return View(superheroes); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(SuperHero superHero) { try { _context.SuperHeroes.Add(superHero); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } catch { return View(); } } public IActionResult Edit(int? id) { var hero = _context.SuperHeroes.Where(s => s.Id == id).FirstOrDefault(); return View(hero); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(int id, SuperHero superHero) { try { _context.Update(superHero); _context.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } public IActionResult Delete(int? id) { var heroToDelete = _context.SuperHeroes.Where(s => s.Id == id).FirstOrDefault(); return View(heroToDelete); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Delete(int id, SuperHero superHero) { try { _context.Remove(superHero); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } catch { return View(); } } public IActionResult Details(int? id) { var heroToDisplay = _context.SuperHeroes.Where(s => s.Id == id).FirstOrDefault(); return View(heroToDisplay); } } }
24ef5843fe02741df8d96f6a849224622920dcca
[ "C#" ]
1
C#
adustin70/Heros-That-Are-Super
b595f3f68d0429518f031daa3390c650cee4ea9b
df1dd2cab3a33ed560882089530de6e01e77d704
refs/heads/master
<file_sep>version: '2' services: nodejs: build: . container_name: nodejs volumes: - .:/user/src/app command: ['/bin/sh', '-c', 'yarn install && yarn run dev'] expose: - "8080" nginx: container_name: nginx image: nginx:stable-alpine restart: unless-stopped environment: VIRTUAL_HOST: www.jameslnwza.com LETSENCRYPT_HOST: www.jameslnwza.com expose: - "80" letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion container_name: nginx-proxy-lets volumes_from: - nginx-proxy volumes: - certs:/etc/nginx/certs:rw - /var/run/docker.sock:/var/run/docker.sock:ro depends_on: - nginx-proxy nginx-proxy: container_name: nginx-proxy image: jwilder/nginx-proxy:alpine restart: always volumes: - ./proxy-config:/etc/nginx/conf.d - certs:/etc/nginx/certs:ro - vhost:/etc/nginx/vhost.d - html:/usr/share/nginx/html - /var/run/docker.sock:/tmp/docker.sock:ro ports: # - host:container - "80:80" - "443:443" volumes: certs: vhost: html:<file_sep>const express = require('express'); const router = require('./app/routes'); const app = express(); const port = 8080; const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); }, }; app.use(express.static('public', options)); app.use(router); app.listen(port); console.log('Server is running at port :', port); <file_sep>const dataStudent = require('../student.json'); const getStudent = (req, res) => { res.status(200).json({ data: dataStudent, }); }; const getStudentById = (req, res) => { const { id } = req.params; const student = dataStudent.find((data) => `${data.id}` === id); if (student) { return res.status(200).json({ data: student }); } return res.status(404).json(`not found student id : ${id}`); }; module.exports = { getStudent, getStudentById, }; <file_sep>const express = require('express'); const controller = require('./controller/studentController'); const router = express.Router(); router.get('/', (req, res) => { res.send('hello nodejs'); }); router.get('/student', controller.getStudent); router.get('/student/:id([0-9]+)', controller.getStudentById); module.exports = router; <file_sep>FROM node:16-slim WORKDIR /user/src/app COPY package.*json . COPY . . RUN yarn install
4ede0601360aaaa5395c3415ed2832bbb2a0fd55
[ "JavaScript", "YAML", "Dockerfile" ]
5
YAML
worawut007/node-express101
789c75cc98b96ca6e3026e655f8d447ec4e932e6
1b4317425e12ee9fc07dbb46df483da59b2d043f
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Member(models.Model): member_name = models.CharField(max_length=50)<file_sep>from django.shortcuts import render # Create your views here. def create_member(request): pass def retrieve_member(request): pass def delete_member(request): pass def update_member(request): pass<file_sep>from django.contrib.auth import login,logout,authenticate,get_user_model from django.shortcuts import render,redirect from .forms import LoginForm, RegisterForm # Create your views here. User = get_user_model() def home_view(request): return render(request,"base.html",{}) def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request,username=username,password=password) if user : login(request,user) return redirect("../") context = { "form":form, } return render(request,"login.html",context) def logout_view(request): logout(request) return redirect("/") def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = User.objects.create_user(username, email, password) return redirect("/login") form = RegisterForm() context = { "form":form, } return render(request,"register.html",context) <file_sep>from django import forms class CreateForm(forms.Form): member_name = forms.CharField()<file_sep>from django.apps import AppConfig class Ch01Config(AppConfig): name = 'ch01' <file_sep>from django.shortcuts import render from django.http import JsonResponse from members.forms import CreateForm from members.models import Member # Create your views here. def create_or_retrieve(request,pk=None): if pk: member = Member.objects.filter(pk=pk) if member: return JsonResponse({ "member_name":member.member_name ,}) return JsonResponse({"error":"member Doesnt exist"}) else: if request.method == "POST": form = CreateForm(request.POST or None) if form.is_valid(): member_name = form.cleaned_data.get("member_name") if member_name: Member.objects.create(member_name=member_name) return JsonResponse({ "member_name":member_name ,}) else: member_list = Member.objects.all() return JsonResponse({ "members":[x.member_name for x in member_list]}) return None def retrieve_member(request,pk): pass def delete_member(request,pk=None): if pk: member = Member.objects.filter(id=pk) if member : member.delete() return JsonResponse({ "status":"Deleted Succesfuly"}) def update_member(request,pk): form = CreateForm(request.POST or None) if form.is_valid(): member_name = form.cleaned_data.get("member_name") obj = Member.objects.get(pk=pk) obj.member_name = member_name obj.save() return JsonResponse({ "status":"Deleted Succesfuly"})<file_sep><div class="login-register border-0" style="margin-top: 20%;"> <div class="showcase"> <h1 class="display-4"> Welcome To Our Family</h1> <p class="text-muted"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat, reprehenderit. </p> </div> <div class="btns"> <div class="login"> <div class="form-group"> <input type="email" class="form-control text-center" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group text-center"> <input type="<PASSWORD>" class="form-control text-center" id="exampleInputPassword1" placeholder="<PASSWORD>"> <a href="" class="btn btn-primary btn-login"> Login </a> </div> </div> <p class="text-center text-muted"> you dont have an account ! | <a href="{% url 'register' %}" class="text-center"> Register </a> </p> </div> </div><file_sep>from django import forms from django.contrib.auth import get_user_model User = get_user_model() class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form_control","placeholder":"Your user name"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form_control","placeholder":"Your Password"})) class RegisterForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form_control","placeholder":"Your user name"})) email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form_control","placeholder":"Your Email"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form_control","placeholder":"Your Password"})) password2 = forms.CharField(label='confirm password',widget=forms.PasswordInput(attrs={"class":"form_control","placeholder":"Confirm your password"})) def clean_password2(self): password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password != password2: raise forms.ValidationError("password must match") return password2 def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username__icontains=username).exists(): raise forms.ValidationError("This User Name already taken") return username def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email__icontains=email).exists(): raise forms.ValidationError("Email already Registred") return email<file_sep>{% load staticfiles %} <!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"> <!-- FontAwesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <title>CSE Challange</title> </head> <body {% if not request.user.is_authenticated %} id="login-page" {% endif %}> {% if request.user.is_authenticated %} {% include "nav-bar-top.html" %} {% endif %} <div> {% block base %} {% if request.user.is_authenticated %} {% include "main-page.html" %} {% else %} <div class="container col-8"> {% include "login_or_register.html" %} </div> {% endif %} {% if request.user.is_authenticated %} {% include "nav-bar-bottom.html" %} {% endif %} {% endblock base %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" ></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" ></script> <script type="text/javascript"> $(document).ready(function (){ var form; $(document.body).on("click",".member-form",function(event){ event.preventDefault(); form = $(this); var formData = form.serialize(); console.log(formData); $.ajax({ url:"{% url 'rest_api:retrieve' %}", method:"GET", success:function(data){ console.log(data); }, error:function(data){ console.log("error "); console.log(data); }, }); }); }); </script> {% block script %} {% endblock script %} </body> </html><file_sep>from django.urls import path,re_path from .views import create_or_retrieve,update_member app_name = 'rest_api' urlpatterns = [ re_path(r'^member/(?P<pk>\d+)/$',create_or_retrieve,name='create'), re_path(r'^member/(?P<pk>\d+)/$',update_member,name='update'), path('member/',create_or_retrieve,name='retrieve' ), ]<file_sep># CSE 1_ create a virtual environment with the command mkvirtualenv "env-name" 2_ install django with the command pip install django 3_ in your machine browse to /challange and run the command python manage.py runserver
01c6b9e968037794085f2704823b4fa97274e2e3
[ "Markdown", "Python", "HTML" ]
11
Python
Abdelbasset-Aidouni/CSE
9237f13ec5f8fec723f492d91f52b995321f860b
1e7c8fe33676949cafed6e09e0207292c7bd2ee9
refs/heads/master
<file_sep>/* * practice.c * * Created on: Nov 4, 2016 * Author: qshan */ #include <stdio.h> #include <stdlib.h> #include <practice.h> //sort##### int sort_int(int Array[], int size_array) { printf("\nHello from %s function!\n", __func__); int i,j; int temp; // for (i=1; i<(sizeof(Array)/sizeof(Array[0]));i++) for (i=1; i<(size_array);i++) { temp = Array[i]; for(j=i-1;j>=0;j--) { if (temp < Array[j]) { Array[j+1] = Array[j]; }else { Array[j+1] = temp; break; } if(j==0) { Array[j] = temp; } } } return 0; } void print_int_array(int Array[], int size_array) { int i=0; printf("Array is {"); for (i=0; i<(size_array);i++) { printf("%d, ", Array[i]); } printf("}"); } //list##### qs_DLIST_PTR qs_dlist_create() { //create the dlist head qs_DLIST_PTR qs_dlist_new_ptr = (qs_DLIST_PTR)malloc(sizeof(qs_DLIST_NODE)); qs_dlist_new_ptr->next = qs_dlist_new_ptr; qs_dlist_new_ptr->piror = qs_dlist_new_ptr; printf("\n%s is ##dlist with head##\n", __func__); printf("\nHere is the end of %s \n", __func__); return qs_dlist_new_ptr; } int qs_dlist_insert_R(qs_DLIST_PTR listptr, qs_DListDataType pos, qs_DListDataType data) { //add code here qs_DLIST_PTR p = listptr; qs_DLIST_PTR newnodeptr; //if list is empty if ((p->next == p) && (p->piror == p)) { printf("current list is empty\n"); printf("insert %d\n", data); newnodeptr = (qs_DLIST_PTR)malloc(sizeof(qs_DLIST_NODE)); newnodeptr->data = data; newnodeptr->next = newnodeptr; newnodeptr->piror = p; p->next= newnodeptr; //listptr = newnodeptr; return 0; } //if find node do{ p = p->next; if ((p->next == p)) { //if this node is in the end or do not find if (p->data != pos) { //therer is no this node printf("not find %d, insert %d in end \n", pos, data); }else { //there is node in the end printf("find %d in end, insert %d \n", pos, data); } newnodeptr = (qs_DLIST_PTR)malloc(sizeof(qs_DLIST_NODE)); newnodeptr->data = data; newnodeptr->next = newnodeptr; newnodeptr->piror = p; p->next = newnodeptr; return 0; }else { // if p->next != p, is not end if (p->data == pos) { //insert node printf("find %d, insert %d \n", pos, data); newnodeptr = (qs_DLIST_PTR)malloc(sizeof(qs_DLIST_NODE)); newnodeptr->data = data; newnodeptr->next = p->next; newnodeptr->piror = p; p->next->piror = newnodeptr; p->next = newnodeptr; return 0; }else { continue; } } }while(1); printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_insert_L() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_delete(qs_DLIST_PTR listptr, qs_DListDataType data) { //add code here qs_DLIST_PTR p = listptr; qs_DLIST_PTR newnodeptr; //if list is empty if ((p->next == p) && (p->piror == p)) { printf("current list is empty\n"); printf("do not find %d\n", data); return 0; } //start search and delete in the list do{ p = p->next; if ((p->next == p)) { //if this node is in the end if (p->data == data) { //data is in the end printf("find %d in end, delete \n", data); newnodeptr = p; p->piror->next = p->piror; //listptr = p->next; free(newnodeptr); return 0; }else { //find next //p = p->next; printf("do not find %d \n", data); return 1; } }else { // if p->next != p if (p->data == data) { //find the data in the list printf("find %d, delete \n", data); newnodeptr = p; p->next->piror = p->piror; p->piror->next = p->next; free(newnodeptr); return 0; }else { //find next continue; } } }while(1); printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_delete_L() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_delete_R() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_print(qs_DLIST_PTR listptr) { //add code here qs_DLIST_PTR p = listptr; printf("current list is: {"); if ((p->next == p) & (p->piror == p)) { printf("empty\n"); //printf("insert %d\n", data); return 0; } while(1) { p = p->next; //scan node printf("%d", p->data); if ((p->next == p)) { printf("}\n"); return 0; } printf(", "); }; printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_length() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_find() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_find_L() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } int qs_dlist_find_R() { //add code here printf("\n Here is the end of %s \n", __func__); return 0; } //int qs_dlist_ListTraverse() #if 1 //queue##### FIFO int qs_InitQueue(qs_QUEUE *Q, int queuesize) { Q->queuesize = (queuesize +1); Q->q = (qs_QueueDataType *)malloc(sizeof(qs_QueueDataType)*(Q->queuesize)); Q->head = 0; Q->tail = 0; printf("Hello from %s \n", __func__); return 0; } int qs_EnQueue(qs_QUEUE *Q, qs_QueueDataType key) { //add code here int tail = ((Q->tail+1) % Q->queuesize); if (tail == Q->head) { printf("this queue is full\n"); printf("not qs_EnQueue %d \n", key); return 1; }else { Q->q[Q->tail] = key; Q->tail = tail; printf("Hello from %s\n", __func__); return 0; } } qs_QueueDataType qs_DeQueue(qs_QUEUE *Q) { //add code here qs_QueueDataType key; if (Q->tail == Q->head) { printf("not DeQueue, queue is empty\n"); return 1; }else { key = Q->q[Q->head]; Q->head = ((Q->head+1) % Q->queuesize); printf("DeQueue, key is %d\n", key); return key; } } int qs_PrintQueue(qs_QUEUE *Q) { //add code here int i; if(Q->head == Q->tail) { printf("empty queue now!\n"); return 1; } printf("This queue is: {"); for (i=0; i< (Q->tail - Q->head);i++) { if (i <((Q->tail - Q->head) - 1)) { printf("%d,", Q->q[Q->head+i]); }else { printf("%d", Q->q[Q->head+i]); } } printf("}\n"); return 0; } //qs_IsQueueEmpty //qs_IsQueueFull #endif #if 1 //linked stack##### LIFO Last In First Out. int qs_lStackInit(qs_LSTACK_NODE_PTR head) { //add code here //head =(qs_LSTACK_NODE_PTR)malloc(sizeof(qs_LSTACK_NODE)); head->next = head; printf("Hello from %s\n", __func__); return 0; } int qs_lStackPush(qs_LSTACK_NODE_PTR head, qs_LStackType data) { qs_LSTACK_NODE_PTR tempptr = (qs_LSTACK_NODE_PTR)malloc(sizeof(qs_LSTACK_NODE)); if (head->next == head) { tempptr->data =data; tempptr->next = tempptr; head->next = tempptr; }else { tempptr->data =data; tempptr->next = head->next; head->next = tempptr; } printf("push %d\n", tempptr->data); return 0; } qs_LStackType qs_lStackPop(qs_LSTACK_NODE_PTR head) { qs_LSTACK_NODE_PTR tempptr = head; qs_LStackType tempdata; if(tempptr->next == tempptr) { printf("no Pop, lStack empty!\n"); return 1; } tempptr = tempptr->next; tempdata = tempptr->data; if (tempptr->next != tempptr) { printf("Pop %d\n", tempptr->data); head->next = tempptr->next; free(tempptr); return tempdata; }else { printf("Pop %d\n", tempptr->data); head->next = head; free(tempptr); return 1; } } int qs_lStackPrint(qs_LSTACK_NODE_PTR head) { qs_LSTACK_NODE_PTR tempptr = head; if(tempptr->next == tempptr) { printf("no print, lStack empty!\n"); return 1; } printf("Current lStack is: {"); tempptr = tempptr->next; while(1) { if (tempptr->next != tempptr) { printf("%d, ", tempptr->data); }else { printf("%d}\n", tempptr->data); break; } tempptr = tempptr->next; } return 0; } #endif #if 0 //tree##### //BFS - Dreadth First Search //DFS - Depth First Search //Tree Traversals, Expression Tree //print node when come to N; N -> node, L -> left child, R -L right child //PreOrderTraversal -> N>L>R //InOrderTraversal -> L>N>R //PostOrderTraversal -> L>R>N #endif #if 0 //graph##### #endif #if 1 //BST - Binary Search Tree qs_BSTREE_PTR qs_CreateBSTNode(qs_BSTreeDataType keynum) { qs_BSTREE_PTR tree = NULL; tree = (qs_BSTREE_PTR)malloc(sizeof(qs_BSTREE_NODE)); tree->data = keynum; tree->lchild = NULL; tree->rchild = NULL; tree->parent = NULL; return tree; } qs_BSTREE_PTR qs_SearchBSTNode(qs_BSTREE_PTR tree, qs_BSTreeDataType number) { while(tree != NULL && number != tree->data) { if (number < tree->data) tree = tree->lchild; else tree = tree->rchild; } return tree; } qs_BSTREE_PTR qs_MinBSTNode(qs_BSTREE_PTR tree) { while(tree->lchild != NULL) { tree = tree->lchild; } return tree; } qs_BSTREE_PTR qs_MaxBSTNode(qs_BSTREE_PTR tree) { while(tree->rchild != NULL) { tree = tree->rchild; } return tree; } qs_BSTREE_PTR qs_BSTSuccessor(qs_BSTREE_PTR tree) { qs_BSTREE_PTR y; if (tree->rchild != NULL) return qs_MinBSTNode(tree->rchild); y = tree->parent; while(y != NULL && tree == y->rchild) { tree = y; y = y->parent; } return y; } qs_BSTREE_PTR qs_BSTPredecessor(qs_BSTREE_PTR tree) { qs_BSTREE_PTR y; if (tree->lchild != NULL) return qs_MaxBSTNode(tree->lchild); y = tree->parent; while(y != NULL && tree == y->lchild) { tree = y; y = y->parent; } return y; } int qs_InsertBSTNode(qs_BSTREE_PTR *tree, qs_BSTREE_PTR z) { qs_BSTREE_PTR x, y; y = NULL; x = *tree; while (x != NULL) { y = x; if (z->data < x->data) x = x->lchild; else x = x->rchild; } z->parent = y; if (y == NULL) *tree = z; else if(z->data < y->data) y->lchild = z; else y->rchild = z; return 0; } //check here to get detail information //http://blog.csdn.net/fengchaokobe/article/details/7551055 int qs_DeleteBSTNode(qs_BSTREE_PTR *tree, qs_BSTREE_PTR z) { qs_BSTREE_PTR x, y; if (z->lchild == NULL || z->rchild == NULL) y = z; else y = qs_BSTSuccessor(&(**tree)); //??? why??? if (y->lchild != NULL) x = y->lchild; else x = y->rchild; if (x != NULL) x->parent = y->parent; if (y->parent == NULL) { (*tree) = x; } else if (y == y->parent->lchild) y->parent->lchild = x; else y->parent->rchild = x; if (y !=z ) z->data = y->data; free(y); y=NULL; return 0; } //BST - Binary Search Tree end #endif #if 0 //AVL Tree #endif #if 0 //B Tree #endif #if 0 //Hashing #endif #if 0 { //add code here printf("\n Here is the end of %s \n", __func__); //printf("\n Here is code line number %d in %s \n", __LINE__, __FILE__); return 0; } #endif <file_sep>#include <stdio.h> int function_shared_test12(int arg0) { printf("-------------------------------------------------- \n"); printf("hi, test12 \n"); printf("Here is the funciton %s \n", __func__); printf("the argo is 0x%x\n",arg0); printf("-------------------------------------------------- \n"); return (arg0 + 1); } <file_sep>#include <stdio.h> #include "uart.h" int uart_api() { #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif printf("hi, test_uart \n"); printf("--------------------------------------------------\n"); return 0; } int uart_init() { #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif return 0; } int _fd = -1; char *_cl_port = NULL; int setup_serial_port(char port_name[], int serial_speed) { #if 1 //PRINT_DEBUG_ENABLE printf("\n-----Run in %s------------------------------\n" ,__func__); //printf("#####Get args port_name:speed \"%s\":%d in %s\n" ,port_name ,serial_speed ,__func__); printf("#####Get args port_name:speed \"%s\":%d in %s\n" ,port_name ,serial_speed ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("-----start setup_serial_port\n"); #endif /* //strdup is in string.h The strdup() function shall return a pointer to a new string on success. Otherwise, it shall return a null pointer and set errno to indicate the error. char *strdup(const char *s); */ _cl_port = strdup(port_name); //_cl_port = port_name; //_cl_port = strdup("/dev/ttyUSB1"); //_cl_port="/dev/ttyUSB1"; /* #define B4800 0000014 */ /* #define B9600 0000015 */ /* #define B19200 0000016 */ /* #define B38400 0000017 */ /* #define B57600 0010001 */ /* #define B115200 0010002 */ /* #define B230400 0010003 */ /* #define B460800 0010004 */ /* #define B500000 0010005 */ /* #define B576000 0010006 */ /* #define B921600 0010007 */ /* #define B1000000 0010010 */ /* #define B1152000 0010011 */ /* #define B1500000 0010012 */ /* #define B2000000 0010013 */ /* #define B2500000 0010014 */ /* #define B3000000 0010015 */ /* #define B3500000 0010016 */ /* #define B4000000 0010017 */ /* #define __MAX_BAUD B4000000 */ //int baud = serial_speed; //int baud = B115200; int baud = (serial_speed == 115200 )?B115200 :(serial_speed == 921600 )?B921600 :(serial_speed == 576000 )?B576000 :(serial_speed == 500000 )?B500000 :(serial_speed == 460800 )?B460800 :(serial_speed == 230400 )?B230400 :(serial_speed == 57600 )?B57600 :(serial_speed == 38400 )?B38400 :(serial_speed == 19200 )?B19200 :(serial_speed == 9600 )?B9600 :(serial_speed == 4800 )?B4800 :B115200; //default config struct termios newtio; int ret; #if PRINT_DEBUG_ENABLE printf("run in \"%s\"\n" ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("_cl_port is \"%s\"\n" ,_cl_port); #endif _fd = open(_cl_port, O_RDWR | O_NONBLOCK); #if PRINT_DEBUG_ENABLE printf("open %s, get _fd is %d\n" ,_cl_port ,_fd); #endif if (_fd < 0) { ret = -errno; perror("Error opening serial port"); exit(ret); } /* Lock device file */ //ToCheck if (flock(_fd, LOCK_EX | LOCK_NB) < 0) { ret = -errno; perror("Error failed to lock device file"); exit(ret); } //ToCheck bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */ /* man termios get more info on below settings */ //newtio.c_cflag = baud | CS8 | CLOCAL | CREAD; newtio.c_cflag = baud | CS8 | CLOCAL | CREAD | PARENB; //newtio.c_cflag = baud | CS8 | CLOCAL | CREAD | PARENB | PARODD; #if 0 newtio.c_cflag &= ~CRTSCTS; newtio.c_cflag &= ~CSTOPB; #endif newtio.c_cflag &= ~CRTSCTS; newtio.c_cflag &= ~CSTOPB; //newtio.c_cflag |= CSTOPB; #if PRINT_DEBUG_ENABLE printf("current newtio.c_cflag is 0x%x\n" ,newtio.c_cflag); printf("current CRTSCTS is 0x%x\n" ,(newtio.c_cflag&CRTSCTS)); printf("current CSTOPB is 0x%x\n" ,(newtio.c_cflag&CSTOPB)); #endif newtio.c_iflag = 0; newtio.c_oflag = 0; newtio.c_lflag = 0; // block for up till 128 characters newtio.c_cc[VMIN] = 128; // 0.5 seconds read timeout newtio.c_cc[VTIME] = 5; /* now clean the modem line and activate the settings for the port */ //ToCheck tcflush(_fd, TCIOFLUSH); //ToCheck tcsetattr(_fd,TCSANOW,&newtio); #if PRINT_DEBUG_ENABLE printf("-----turn on the serial\n"); #endif return 0; } int setup_serial_port_01(char port_name[], int serial_speed) { #if 1 //PRINT_DEBUG_ENABLE printf("\n-----Run in %s------------------------------\n" ,__func__); printf("#####Get args port_name:speed \"%s\":%d in %s\n" ,port_name ,serial_speed ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("-----start setup_serial_port\n"); #endif _cl_port = strdup(port_name); int baud = (serial_speed == 115200 )?B115200 :(serial_speed == 921600 )?B921600 :(serial_speed == 576000 )?B576000 :(serial_speed == 500000 )?B500000 :(serial_speed == 460800 )?B460800 :(serial_speed == 230400 )?B230400 :(serial_speed == 57600 )?B57600 :(serial_speed == 38400 )?B38400 :(serial_speed == 19200 )?B19200 :(serial_speed == 9600 )?B9600 :(serial_speed == 4800 )?B4800 :B115200; //default config struct termios newtio; int ret; #if PRINT_DEBUG_ENABLE printf("run in \"%s\"\n" ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("_cl_port is \"%s\"\n" ,_cl_port); #endif _fd = open(_cl_port, O_RDWR | O_NONBLOCK); #if PRINT_DEBUG_ENABLE printf("open %s, get _fd is %d\n" ,_cl_port ,_fd); #endif if (_fd < 0) { ret = -errno; perror("Error opening serial port"); exit(ret); } /* Lock device file */ //ToCheck if (flock(_fd, LOCK_EX | LOCK_NB) < 0) { ret = -errno; perror("Error failed to lock device file"); exit(ret); } //ToCheck bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */ /* man termios get more info on below settings */ //newtio.c_cflag = baud | CS8 | CLOCAL | CREAD; newtio.c_cflag = baud | CS8 | CLOCAL | CREAD | PARENB; //newtio.c_cflag = baud | CS8 | CLOCAL | CREAD | PARENB | PARODD; #if 0 newtio.c_cflag &= ~CRTSCTS; newtio.c_cflag &= ~CSTOPB; #endif newtio.c_cflag &= ~CRTSCTS; newtio.c_cflag &= ~CSTOPB; //newtio.c_cflag |= CSTOPB; #if PRINT_DEBUG_ENABLE printf("current newtio.c_cflag is 0x%x\n" ,newtio.c_cflag); printf("current CRTSCTS is 0x%x\n" ,(newtio.c_cflag&CRTSCTS)); printf("current CSTOPB is 0x%x\n" ,(newtio.c_cflag&CSTOPB)); #endif newtio.c_iflag = 0; newtio.c_oflag = 0; newtio.c_lflag = 0; // block for up till 128 characters newtio.c_cc[VMIN] = 128; // 0.5 seconds read timeout newtio.c_cc[VTIME] = 5; /* now clean the modem line and activate the settings for the port */ //ToCheck tcflush(_fd, TCIOFLUSH); //ToCheck tcsetattr(_fd,TCSANOW,&newtio); #if PRINT_DEBUG_ENABLE printf("-----turn on the serial\n"); #endif return 0; } void clear_custom_speed_flag() { struct serial_struct ss; int ret; //ToCheck if (ioctl(_fd, TIOCGSERIAL, &ss) < 0) { // return silently as some devices do not support TIOCGSERIAL return; } if ((ss.flags & ASYNC_SPD_MASK) != ASYNC_SPD_CUST) return; ss.flags &= ~ASYNC_SPD_MASK; if (ioctl(_fd, TIOCSSERIAL, &ss) < 0) { ret = -errno; perror("TIOCSSERIAL failed"); exit(ret); } } int write_hello_string() { #if PRINT_DEBUG_ENABLE printf("-----start try to send one string\n"); #endif int written; unsigned char hello_string[]="hello from uart_test!\n"; int string_number = sizeof(hello_string); written = write(_fd, &hello_string ,string_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE printf("-----send \"%s\"\n" ,hello_string); #endif if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != string_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, string_number); exit(-EIO); } return 0; } unsigned int write_order_hex() { #if PRINT_DEBUG_ENABLE printf("-----start try to send one string\n"); #endif int written; //unsigned char hello_string[]="01FEDCBA9876543210"; //unsigned char hello_string[]="010123456789abcdef"; //unsigned char hello_hex[]={0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35 ,0x36 ,0x37 ,0x38 ,0x39 ,0x3a ,0x3b ,0x3c ,0x3d ,0x3e ,0x3f}; unsigned char hello_hex[]={0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //int hello_hex[]={0x01 ,0x76543210 ,0xfedcba98}; int hello_hex_number = sizeof(hello_hex); //written = write(_fd, &hello_string ,string_number); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is in %s\n" ,__func__); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); //printf("-----send \"%s\"\n" ,hello_hex); #endif if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } return 0; } //write the contents into register with uart unsigned int write_out_hex_with_reorder(int addr ,int data) { unsigned int data_returned; #if PRINT_DEBUG_ENABLE printf("\n-----Run in %s\n" ,__func__); printf("-----start try to send 0x%x 0x%x\n" ,addr ,data); #endif int written; //unsigned char hello_string[]="01FEDCBA9876543210"; //unsigned char hello_string[]="010123456789abcdef"; //unsigned char hello_hex[]={0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35 ,0x36 ,0x37 ,0x38 ,0x39 ,0x3a ,0x3b ,0x3c ,0x3d ,0x3e ,0x3f}; //unsigned int hello_hex[9]={0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //unsigned char hello_hex[9]={0x01 ,0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; unsigned char hello_hex[CMD_WRITE_PACKAGE_LEN]={CMD_CODE_WRITE ,0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; hello_hex[0] = CMD_CODE_WRITE; hello_hex[1] = ((addr >> 0) & 0xff); hello_hex[2] = ((addr >> 8) & 0xff); hello_hex[3] = ((addr >> 16) & 0xff); hello_hex[4] = ((addr >> 24) & 0xff); hello_hex[5] = ((data >> 0) & 0xff); hello_hex[6] = ((data >> 8) & 0xff); hello_hex[7] = ((data >> 16) & 0xff); hello_hex[8] = ((data >> 24) & 0xff); #if 0 int i; for (i=0;i<CMD_WRITE_PACKAGE_LEN;i++) { hello_hex[i] = ((hello_hex[i] >> 4) & 0xf) | ((hello_hex[i] << 4) & 0xf0); } #endif //int hello_hex[]={0x01 ,0x76543210 ,0xfedcba98}; int hello_hex_number = sizeof(hello_hex); //written = write(_fd, &hello_string ,string_number); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is in %s\n" ,__func__); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); //printf("-----send \"%s\"\n" ,hello_hex); #endif #if PRINT_DEBUG_ENABLE if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } #endif #if PRINT_DEBUG_ENABLE printf("Try to delay 100ms delay\n"); #endif usleep(100000); //int usleep(useconds_t usec); //int usleep(useconds_t usec); //<unistd.h> #if 1 //read ack info //poll_data_one_time_without_while(); data_returned = poll_data_one_time_without_while(); #endif return data_returned; //return 0; } //write the contents into register with uart unsigned int write_out_hex_with_reorder_01(int addr ,int data) { unsigned int data_returned; #if PRINT_DEBUG_ENABLE printf("\n-----Run in %s\n" ,__func__); printf("-----start try to send 0x%x 0x%x\n" ,addr ,data); #endif int written; unsigned char hello_hex[CMD_WRITE_PACKAGE_LEN]={CMD_CODE_WRITE ,0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; hello_hex[0] = CMD_CODE_WRITE; hello_hex[1] = ((addr >> 0) & 0xff); hello_hex[2] = ((addr >> 8) & 0xff); hello_hex[3] = ((addr >> 16) & 0xff); hello_hex[4] = ((addr >> 24) & 0xff); hello_hex[5] = ((data >> 0) & 0xff); hello_hex[6] = ((data >> 8) & 0xff); hello_hex[7] = ((data >> 16) & 0xff); hello_hex[8] = ((data >> 24) & 0xff); int hello_hex_number = sizeof(hello_hex); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is in %s\n" ,__func__); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); #endif #if PRINT_DEBUG_ENABLE if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } #endif #if PRINT_DEBUG_ENABLE printf("Try to delay 100ms delay\n"); #endif usleep(100000); //int usleep(useconds_t usec);//<unistd.h> #if 1 //read ack info data_returned = poll_data_one_time_without_while_01(); #endif return data_returned; } unsigned int read_one_time_string() { //ToCheck struct pollfd serial_poll; serial_poll.fd = _fd; serial_poll.events |= POLLIN; //serial_poll.events |= POLLOUT; serial_poll.events &= ~POLLOUT; ///* Event types that can be polled for. These bits may be set in `events' //to indicate the interesting event types; they will appear in `revents' //to indicate the status of the file descriptor. */ //#define POLLIN 0x001 /* There is data to read. */ //#define POLLPRI 0x002 /* There is urgent data to read. */ //#define POLLOUT 0x004 /* Writing now will not block. */ #if PRINT_DEBUG_ENABLE printf("current is serial_poll.events 0x%x\n" ,serial_poll.events); printf("current is serial_poll.revents 0x%x\n" ,serial_poll.revents); #endif //try to poll status //TODO// while(1) { int serial_port_timeout_number = 1000; //unit is milliseconds //extern int poll (struct pollfd *__fds, nfds_t __nfds, int __timeout); //int retval = poll(&serial_poll, 1, 1000); //int retval = poll(&serial_poll, 1, serial_port_timeout_number); #if PRINT_DEBUG_ENABLE int retval = #endif poll(&serial_poll, 1, serial_port_timeout_number); #if PRINT_DEBUG_ENABLE printf("Check retval : serial_poll.revents is %d:0x%x\n" ,retval ,serial_poll.revents); #endif if (serial_poll.revents & POLLIN) { #if PRINT_DEBUG_ENABLE printf("Read data now\n"); #endif //read operation here { unsigned char rb[BUFFER_RECEIVED_SIZE]; //ToCheck #if PRINT_DEBUG_ENABLE int c = #endif read(_fd, &rb, sizeof(rb)); #if PRINT_DEBUG_ENABLE printf("Get data, number is 0x%x, rb is \"%s\"\n" ,c ,rb); int j; printf("get data: hex format is\n"); for (j=0; j < c; j++) { printf("%02x ", rb[j]); } printf("\n"); #endif } break; } //Debug//break; } return 0; } //read the contents from register with uart unsigned int read_in_hex_with_reorder(int addr) { #if PRINT_DEBUG_ENABLE printf("\n-----Run in %s\n" ,__func__); //printf("-----start try to send 0x%x 0x%x\n" ,addr ,data); printf("-----start try to read 0x%x\n" ,addr); #endif //int data ,read_count; int written; //unsigned char hello_string[]="01FEDCBA9876543210"; //unsigned char hello_string[]="010123456789abcdef"; //unsigned char hello_hex[]={0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35 ,0x36 ,0x37 ,0x38 ,0x39 ,0x3a ,0x3b ,0x3c ,0x3d ,0x3e ,0x3f}; //unsigned int hello_hex[9]={0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //unsigned char hello_hex[9]={0x01 ,0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //unsigned char hello_hex[5]={0x11 ,0x01 ,0x23 ,0x45 ,0x67}; //unsigned char hello_hex[5]={0x11 ,0x01 ,0x23 ,0x45 ,0x67}; unsigned char hello_hex[CMD_READ_PACKAGE_LEN]={CMD_CODE_READ ,0x01 ,0x23 ,0x45 ,0x67}; hello_hex[0] = CMD_CODE_READ; hello_hex[1] = ((addr >> 0) & 0xff); hello_hex[2] = ((addr >> 8) & 0xff); hello_hex[3] = ((addr >> 16) & 0xff); hello_hex[4] = ((addr >> 24) & 0xff); //hello_hex[5] = ((data >> 0) & 0xff); //hello_hex[6] = ((data >> 8) & 0xff); //hello_hex[7] = ((data >> 16) & 0xff); //hello_hex[8] = ((data >> 24) & 0xff); #if 0 int i; for (i=0;i<CMD_READ_PACKAGE_LEN;i++) { hello_hex[i] = ((hello_hex[i] >> 4) & 0xf) | ((hello_hex[i] << 4) & 0xf0); } #endif //int hello_hex[]={0x01 ,0x76543210 ,0xfedcba98}; int hello_hex_number = sizeof(hello_hex); //written = write(_fd, &hello_string ,string_number); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is\n"); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); //printf("-----send \"%s\"\n" ,hello_hex); #endif #if PRINT_DEBUG_ENABLE if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } #endif #if PRINT_DEBUG_ENABLE printf("Try to delay 100ms delay\n"); #endif usleep(100000); //int usleep(useconds_t usec); return poll_data_one_time_without_while(); //return 0; } //read the contents from register with uart unsigned int read_in_hex_with_reorder_01(int addr) { #if PRINT_DEBUG_ENABLE printf("\n-----Run in %s\n" ,__func__); printf("-----start try to read 0x%x\n" ,addr); #endif int written; unsigned char hello_hex[CMD_READ_PACKAGE_LEN]={CMD_CODE_READ ,0x01 ,0x23 ,0x45 ,0x67}; hello_hex[0] = CMD_CODE_READ; hello_hex[1] = ((addr >> 0) & 0xff); hello_hex[2] = ((addr >> 8) & 0xff); hello_hex[3] = ((addr >> 16) & 0xff); hello_hex[4] = ((addr >> 24) & 0xff); #if 0 int i; for (i=0;i<CMD_READ_PACKAGE_LEN;i++) { hello_hex[i] = ((hello_hex[i] >> 4) & 0xf) | ((hello_hex[i] << 4) & 0xf0); } #endif int hello_hex_number = sizeof(hello_hex); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is\n"); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); #endif #if PRINT_DEBUG_ENABLE if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } #endif #if PRINT_DEBUG_ENABLE printf("Try to delay 100ms delay\n"); #endif usleep(100000); //int usleep(useconds_t usec); return poll_data_one_time_without_while_01(); } unsigned int poll_data_one_time_without_while() { struct pollfd serial_poll; serial_poll.fd = _fd; serial_poll.events |= POLLIN; serial_poll.events &= ~POLLOUT; //int retval = poll(&serial_poll, 1, 1000); //int retval = poll(&serial_poll, 1, 100); poll(&serial_poll, 1, 100); #if PRINT_DEBUG_ENABLE printf("current is serial_poll.events 0x%x\n" ,serial_poll.events); printf("current is serial_poll.revents 0x%x\n" ,serial_poll.revents); #endif //TODO//size need update according the realy application //unsigned char data_get_hex[4]={0x01 ,0x23 ,0x45 ,0x67}; //unsigned char data_get_hex[1024]={0x01 ,0x23 ,0x45 ,0x67}; unsigned int data_get_hex=0x1234567; if (serial_poll.revents & POLLIN) { unsigned char rb[BUFFER_RECEIVED_SIZE]; int c = read(_fd, &rb, sizeof(rb)); #if PRINT_DEBUG_ENABLE int j; printf("get data: hex format is\n"); for (j=0; j < c; j++) { printf("%02x ", rb[j]); } printf("\n"); #endif switch (c) { case 1 : //get the ack for write //data_get_hex[0] = rb[0]; data_get_hex = (unsigned int) rb[0]; //return (unsigned int) rb[0]; break; case 5 : //unsigned char data_get_hex[5]={0x11 ,0x01 ,0x23 ,0x45 ,0x67}; /* unsigned char data_get_hex[4]={0x01 ,0x23 ,0x45 ,0x67}; */ /* data_get_hex[0] = rb[c-1]; */ /* data_get_hex[1] = rb[c-2]; */ /* data_get_hex[2] = rb[c-3]; */ /* data_get_hex[3] = rb[c-4]; */ data_get_hex = (0 | ( (rb[c-4] << 0 ) & 0xff ) | ( (rb[c-3] << 8 ) & 0xff00 ) | ( (rb[c-2] << 16) & 0xff0000 ) | ( (rb[c-1] << 24) & 0xff000000 ) /* | rb[c-4] << 0 */ /* | rb[c-3] << 8 */ /* | rb[c-2] << 16 */ /* | rb[c-1] << 24 */ ); #if PRINT_DEBUG_ENABLE printf("get the ack 0x%x in %s\n" ,(unsigned int) rb[0] ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("get the data 0x%08x in %s\n" ,data_get_hex ,__func__); #endif //return (unsigned int) data_get_hex; break; default : #if 1 printf("received data ###error### %d\n" ,c); #endif #if PRINT_DEBUG_ENABLE int j; printf("get data: hex format is\n"); for (j=0; j < c; j++) { printf("%02x ", rb[j]); } printf("\n"); #endif data_get_hex = (0 | ( (rb[c-4] << 0 ) & 0xff ) | ( (rb[c-3] << 8 ) & 0xff00 ) | ( (rb[c-2] << 16) & 0xff0000 ) | ( (rb[c-1] << 24) & 0xff000000 ) ); } } #if PRINT_DEBUG_ENABLE printf("#####Return data_get_hex: 0x%08x in %s\n" ,data_get_hex ,__func__); #endif return data_get_hex; //return (unsigned int) data_get_hex; //return 0; } unsigned int poll_data_one_time_without_while_01() { struct pollfd serial_poll; serial_poll.fd = _fd; serial_poll.events |= POLLIN; serial_poll.events &= ~POLLOUT; poll(&serial_poll, 1, 100); #if PRINT_DEBUG_ENABLE printf("current is serial_poll.events 0x%x\n" ,serial_poll.events); printf("current is serial_poll.revents 0x%x\n" ,serial_poll.revents); #endif unsigned int data_get_hex=0x1234567; if (serial_poll.revents & POLLIN) { unsigned char rb[BUFFER_RECEIVED_SIZE]; int c = read(_fd, &rb, sizeof(rb)); #if PRINT_DEBUG_ENABLE int j; printf("get data: hex format is\n"); for (j=0; j < c; j++) { printf("%02x ", rb[j]); } printf("\n"); #endif switch (c) { case 1 : //get the ack for write data_get_hex = (unsigned int) rb[0]; break; case 5 : data_get_hex = (0 | ( (rb[c-4] << 0 ) & 0xff ) | ( (rb[c-3] << 8 ) & 0xff00 ) | ( (rb[c-2] << 16) & 0xff0000 ) | ( (rb[c-1] << 24) & 0xff000000 ) ); #if PRINT_DEBUG_ENABLE printf("get the ack 0x%x in %s\n" ,(unsigned int) rb[0] ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("get the data 0x%08x in %s\n" ,data_get_hex ,__func__); #endif break; default : #if 1 printf("received data ###error### %d\n" ,c); #endif #if PRINT_DEBUG_ENABLE int j; printf("get data: hex format is\n"); for (j=0; j < c; j++) { printf("%02x ", rb[j]); } printf("\n"); #endif data_get_hex = (0 | ( (rb[c-4] << 0 ) & 0xff ) | ( (rb[c-3] << 8 ) & 0xff00 ) | ( (rb[c-2] << 16) & 0xff0000 ) | ( (rb[c-1] << 24) & 0xff000000 ) ); } } #if PRINT_DEBUG_ENABLE printf("#####Return data_get_hex: 0x%08x in %s\n" ,data_get_hex ,__func__); #endif return data_get_hex; } unsigned int read_in_hex_with_reorder_send_comand_only(int addr) { #if PRINT_DEBUG_ENABLE printf("\n-----Run in %s\n" ,__func__); //printf("-----start try to send 0x%x 0x%x\n" ,addr ,data); printf("-----start try to read 0x%x\n" ,addr); #endif //int data ,read_count; int written; //unsigned char hello_string[]="01FEDCBA9876543210"; //unsigned char hello_string[]="010123456789abcdef"; //unsigned char hello_hex[]={0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35 ,0x36 ,0x37 ,0x38 ,0x39 ,0x3a ,0x3b ,0x3c ,0x3d ,0x3e ,0x3f}; //unsigned int hello_hex[9]={0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //unsigned char hello_hex[9]={0x01 ,0x01 ,0x23 ,0x45 ,0x67 ,0x89 ,0xab ,0xcd ,0xef}; //unsigned char hello_hex[5]={0x11 ,0x01 ,0x23 ,0x45 ,0x67}; unsigned char hello_hex[CMD_READ_PACKAGE_LEN]={CMD_CODE_READ ,0x01 ,0x23 ,0x45 ,0x67}; hello_hex[0] = CMD_CODE_READ; hello_hex[1] = ((addr >> 0) & 0xff); hello_hex[2] = ((addr >> 8) & 0xff); hello_hex[3] = ((addr >> 16) & 0xff); hello_hex[4] = ((addr >> 24) & 0xff); //hello_hex[5] = ((data >> 0) & 0xff); //hello_hex[6] = ((data >> 8) & 0xff); //hello_hex[7] = ((data >> 16) & 0xff); //hello_hex[8] = ((data >> 24) & 0xff); #if 0 int i; for (i=0;i<CMD_READ_PACKAGE_LEN;i++) { hello_hex[i] = ((hello_hex[i] >> 4) & 0xf) | ((hello_hex[i] << 4) & 0xf0); } #endif //int hello_hex[]={0x01 ,0x76543210 ,0xfedcba98}; int hello_hex_number = sizeof(hello_hex); //written = write(_fd, &hello_string ,string_number); written = write(_fd, hello_hex, hello_hex_number); #if PRINT_DEBUG_ENABLE printf("-----send %d byte out\n" ,written); #endif #if PRINT_DEBUG_ENABLE int k; printf("Send data: hex format is\n"); for (k=0; k < written; k++) { printf("%02x ", hello_hex[k]); } printf("\n"); //printf("-----send \"%s\"\n" ,hello_hex); #endif #if PRINT_DEBUG_ENABLE if (written < 0) { int ret = errno; perror("write()"); exit(ret); } else if (written != hello_hex_number) { fprintf(stderr, "ERROR: write() returned %d, not %d\n", written, hello_hex_number); exit(-EIO); } #endif return 0; } unsigned int or_write_register(int addr ,int data) { unsigned int temp_data; #if PRINT_DEBUG_ENABLE printf("\n-----Run in [%s]------------------------------\n" ,__func__); printf("#####Get args addr:data 0x%08x:0x%08x in %s\n" ,addr ,data ,__func__); #endif //temp_data = write_out_hex_with_reorder(addr ,data); temp_data = write_out_hex_with_reorder_01(addr ,data); #if 1 //PRINT_DEBUG_ENABLE printf("#####Write addr:data [0x%08x:0x%08x], Get _ack:[0x%08x]\n" ,addr ,data ,temp_data); #endif return temp_data; } unsigned int ir_read_register(int addr) { unsigned int temp_data; #if PRINT_DEBUG_ENABLE printf("\n-----Run in [%s]------------------------------\n" ,__func__); printf("#####Get args addr 0x%08x in %s\n" ,addr ,__func__); #endif //temp_data = read_in_hex_with_reorder(addr); temp_data = read_in_hex_with_reorder_01(addr); #if 1 //PRINT_DEBUG_ENABLE printf("#####Read addr:[0x%08x], Get data:[0x%08x]\n" ,addr ,temp_data); #endif return temp_data; } //static void exit_handler(void) void exit_handler() { if (_fd >= 0) { flock(_fd, LOCK_UN); close(_fd); } if (_cl_port) { free(_cl_port); _cl_port = NULL; } // if (_write_data) { // free(_write_data); // _write_data = NULL; // } } <file_sep>#ifndef __TEST13_H__ #define __TEST13_H__ #include "test13_shared.h" #include "say_hello_13.h" #endif <file_sep>#ifndef __SAY_HELLO__H__ #define __SAY_HELLO__H__ int say_hello(); #endif <file_sep>#Library('',[]) #Library('Test11SharedLib', ['../src_shared/test11_shared.c']) #Library('Test11SharedLib', ['../src_shared/test11_shared.c'] ,CPPPATH=['../include']) #Program('',[]) #Program('test11' ,['../src/test11.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_11.c'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['../src/test11.c' ,'../src/say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['test11.c' ,'say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) #Program('test11' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) Import("env") Import("opt") Import("dbg") # #env.Program('test11' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../build_sc_shared']) #env.Program('test11' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) env.Program('test11' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) #opt.Program('test11-opt' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) #dbg.Program('test11-dbg' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['../src_shared']) <file_sep>#!/bin/bash ctags_Re libs_shared/ libs/ test <file_sep>#!/bin/bash # run like this export Test14BuildPath="./build_cmake2" if [ ! -d ${Test14BuildPath} ]; then mkdir -p ${Test14BuildPath} fi if [ -d ${Test14BuildPath} ]; then cd ${Test14BuildPath} #cmake -G "Unix Makefiles" .. cmake .. make clean make # ./Test14_Hello # ./test14 ./test14 arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 --File /home/data/outputdata.txt cd - # mkdir build_cmake fi <file_sep>#include <stdio.h> #include "string.h" //macro and data type here #define MAX_STRING_LENGTH 100 //function list int arg_read(int argc ,char *argv[], char input_arg_list[][3][MAX_STRING_LENGTH]); int print_arg_list(char input_arg_list[][3][MAX_STRING_LENGTH]); int arg_read(int argc ,char *argv[] ,char input_arg_list[][3][MAX_STRING_LENGTH]) { int i, j;//for arg print control int value_returned=0; #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif #if 1 { //ToCheck /* #define MAX_STRING_LENGTH 100 char input_arg_list[][3][MAX_STRING_LENGTH]= { {"--port" ,"" ,"set port name info"} ,{"--file" ,"" ,"set file name"} ,{"--end--" ,"--end--" ,"reserved keywords"} }; */ printf("------------------------------\n"); if ((strcasecmp (argv[1], "--help") == 0)) { printf("##### Help arguments format:\n"); printf("##### --keyword key_value_need_input\n"); printf("##### keyword supported lists:\n"); for (j=0;;j++) { if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list[j][0] ,input_arg_list[j][2]); } //return 1 value_returned =1; } else { for(i=1;i<argc;) { for (j=0;;j++) { if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} if ((strcasecmp (argv[i], input_arg_list[j][0]) == 0)) { strncpy(input_arg_list[j][1], argv[i+1] ,strlen(argv[i+1])); printf("##### Get %s info: %s\n" ,input_arg_list[j][0] ,input_arg_list[j][1]); } } i=i+2; } //return 0 value_returned =0; } } #endif //return 0; return value_returned; } int print_arg_list(char input_arg_list[][3][MAX_STRING_LENGTH]) { int value_returned =0; int i=0; #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif printf("------------------------------\n"); printf("check the input_arg_list info\n"); for (i=0;;i++) { if ((strcasecmp (input_arg_list[i][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list[i][0] ,input_arg_list[i][1]); } return value_returned; } int main(int argc ,char *argv[]) //int main_try(int argc ,char *argv[]) { int value_returned=0; #if PRINT_DEBUG_ENABLE printf("\n"); printf("===================================================\n"); printf("hello read_argu \n"); printf("\n"); #endif #if 1 { int i=0; printf("------------------------------\n"); printf("##### Get argc is %d\n" , argc); printf("##### Get argv is "); for(i=0;i<argc;i++) { printf(" %s" , argv[i]); } printf("\n"); printf("------------------------------\n"); for(i=0;i<argc;i++) { printf("##### Get argv[%d] is %s\n" ,i ,argv[i]); } } #endif #if 1 { //ToCheck //#define MAX_STRING_LENGTH 100 char input_arg_list1[][3][MAX_STRING_LENGTH]= { {"--port" ,"" ,"set port name info"} ,{"--file" ,"" ,"set file name"} ,{"--end--" ,"--end--" ,"reserved keywords"} }; #if 1 //check the argument list contents before updated print_arg_list(input_arg_list1); #endif printf("------------------------------\n"); printf("Start call arg_read function\n"); value_returned = arg_read(argc ,argv ,input_arg_list1); printf("exit arg_read function now\n"); #if 0 int i=0; printf("------------------------------\n"); printf("check the input_arg_list info\n"); for (i=0;;i++) { if ((strcasecmp (input_arg_list1[i][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list1[i][0] ,input_arg_list1[i][1]); } #endif #if 1 //check the argument list contents updated print_arg_list(input_arg_list1); #endif } #endif #if PRINT_DEBUG_ENABLE printf("\n"); printf("Bye read_argu \n"); printf("===================================================\n"); printf("\n"); #endif printf("------------------------------\n"); printf("value_returned is %d\n" ,value_returned); return value_returned; } <file_sep># run like this #for gcc make make clean make #./build_gcc/test09 make run #for cmake + make case #cd ./build ##cmake -G "Unix Makefiles" .. #cmake .. #make #./Test09_Hello <file_sep>#ifndef __SAY_HELLO_09_H__ #define __SAY_HELLO_09_H__ int say_hello09(); #endif <file_sep>/* * practice.h * * Created on: Nov 4, 2016 * Author: qshan */ #ifndef SRC_QSHAN_PRACTICE_H_ #define SRC_QSHAN_PRACTICE_H_ #include <stdio.h> #include <stdlib.h> #ifndef NULL #ifdef(__cplusplus) #define NULL 0 #else #define NULL ((void *)0) #endif #endif #define NUMBEROFARRAYD1(x) (int)(sizeof(x)/sizeof(x[0])) //there is 3 power state definition here: #define POWER_OFF 0 #define POWER_ON 1 #define LOW_POWER 3 #define POWER_MODE_TRAN_ENABLE 1 #define POWER_MODE_TRAN_DISABLE 0 //here is a global power state definition extern unsigned int SocSystemPowerState; extern unsigned int LoadCPUImageReady; //just for Core1~3,set by cmm extern unsigned int LoadCPUImageRequest; //set by Core0 in C extern unsigned int LoadWifiReady; //set by cmm, to load wifi image, how get the wifi feedback? extern unsigned int LoadWifiRequest; //set by Core0 in C extern unsigned int SystemError; extern unsigned int SystemNum; extern unsigned int PowerOnEnable; extern unsigned int LowPowerEnterEnable; extern unsigned int LowPowerExitEnable; typedef long unsigned int LUI_NUB; //define the dlinst #if 1 //qs_DListDataType #define qs_DListDataType int struct dlist_node{ qs_DListDataType data; struct dlist_node *piror, *next; }; typedef struct dlist_node qs_DLIST_NODE; typedef struct dlist_node *qs_DLIST_PTR; //typedef qs_DLIST_NODE *qs_DLIST_PTR; #else typedef struct dlist_node{ qs_DListDataType data; struct dlist_node *piror, *next; } qs_DLIST_NODE, *qs_DLIST_PTR; #endif //declare a struct //qs_DLIST_NODE struct_customer_name; //declare a pointer of struct //qs_DLIST_PTR struct_customer_pointer; //qs_DLIST_NODE *struct_customer_pointer; //qs_Queue #define qs_QueueDataType int typedef struct queue { //this struct need a cell to diff the full and empty int queuesize; int head,tail; qs_QueueDataType *q; } qs_QUEUE; //qs_LStack #define qs_LStackType int typedef struct lStackNode{ qs_LStackType data; struct lStackNode *next; } qs_LSTACK_NODE, *qs_LSTACK_NODE_PTR; //qs_BiTree #define qs_TreeDataType int typedef struct BiTNode { qs_TreeDataType data; struct BiTNode *parent, *lchild, *rchild; } qs_BITREE_NODE, *qs_BITREE_PTR; //qs_BinarySearchTree #define qs_BSTreeDataType int typedef struct BinarySearchTreeNode { qs_BSTreeDataType data; //the data of this node //int data_index; //the location of data in data array struct BinarySearchTreeNode *parent, *lchild, *rchild; } qs_BSTREE_NODE, *qs_BSTREE_PTR; qs_BSTREE_PTR qs_CreateBSTNode(qs_BSTreeDataType keynum); qs_BSTREE_PTR qs_SearchBSTNode(qs_BSTREE_PTR tree, qs_BSTreeDataType number); qs_BSTREE_PTR qs_MinBSTNode(qs_BSTREE_PTR tree); qs_BSTREE_PTR qs_MaxBSTNode(qs_BSTREE_PTR tree); qs_BSTREE_PTR qs_BSTSuccessor(qs_BSTREE_PTR tree); qs_BSTREE_PTR qs_BSTPredecessor(qs_BSTREE_PTR tree); int qs_InsertBSTNode(qs_BSTREE_PTR *tree, qs_BSTREE_PTR z); int qs_DeleteBSTNode(qs_BSTREE_PTR *tree, qs_BSTREE_PTR z); //the storage format for Tree /////1)parent format //qs_PTreeMaxDataSize is total node number of this tree. //nodes[r].parent is 0 when this node is root node //nodes[i].data is the data of this node //nodes[i].parent is the location of its parent. in the array? #define qs_PTreeMaxDataSize 100 typedef int qs_PTreeElemDataType; typedef struct PTreeNode { qs_PTreeElemDataType data; //data of this node int parent_index; // the location of it parent in the array } qs_PTREENODE; typedef struct { qs_PTREENODE nodes[qs_PTreeMaxDataSize]; //array for the data of tree nodes int r, NumberOfNodes; //location of root node, and number of nodes } qs_PTREE; /////2)child format //qs_ChildTreeMaxDataSize is total number of this tree's child lists. //suppose there is degree k for very parent node, that means there is k child for very parent node //there are multi-child in root node //there is list in every child node. // #define qs_ChildTreeMaxDataSize 100 typedef int qs_ChildTreeElemDataType; typedef struct ChildTreeNode { //qs_ChildTreeElemDataType data; //data of this child int child_index; //the location of child node struct ChildTreeNode *next_ptr; //pointer to next child in this node } qs_CHILDTREENODE, *qs_CHILDTREENODE_PTR; typedef struct ChildTreeNodeBox //head structure { qs_ChildTreeElemDataType data; qs_CHILDTREENODE_PTR firstchild_ptr; //the pointer of child list. //int degree; //this is optional parameter } qs_ChildTreeNodeBox; typedef struct { qs_ChildTreeNodeBox nodes[qs_ChildTreeMaxDataSize]; //array for child list int root_index, NumberOfNodes; //location of root node, and number of total nodes } qs_CHILDTREE; /////3)child sibling format //#define qs_CSTreeMaxDataSize 100 typedef int qs_CSTreeElemDataType; typedef struct CSTreeNode { qs_CSTreeElemDataType data; //data of this node struct CSTreeNode *firstchild, *rightsibling; //int parent; // the location of it parent in the array } qs_CSTREENODE, *qs_CSTREE_PTR; //////// function name list here //sort##### int sort_int(int Array[], int size_array); void print_int_array(int Array[], int size_array); //list##### qs_DLIST_PTR qs_dlist_create(); int qs_dlist_insert_R(qs_DLIST_PTR listptr, qs_DListDataType pos, qs_DListDataType data); int qs_dlist_insert_L(); int qs_dlist_delete(qs_DLIST_PTR listptr, qs_DListDataType data); int qs_dlist_delete_L(); int qs_dlist_delete_R(); int qs_dlist_print(qs_DLIST_PTR listptr); int qs_dlist_length(); int qs_dlist_find(); int qs_dlist_find_L(); int qs_dlist_find_R(); // //queue##### FIFO int qs_InitQueue(qs_QUEUE *Q, int queuesize); int qs_EnQueue(qs_QUEUE *Q, qs_QueueDataType key); qs_QueueDataType qs_DeQueue(qs_QUEUE *Q); int qs_PrintQueue(qs_QUEUE *Q); //qs_IsQueueEmpty //qs_IsQueueFull //linked stack##### LIFO Last In First Out. int qs_lStackInit(qs_LSTACK_NODE_PTR head); int qs_lStackPush(qs_LSTACK_NODE_PTR head, qs_LStackType data); qs_LStackType qs_lStackPop(qs_LSTACK_NODE_PTR head); int qs_lStackPrint(qs_LSTACK_NODE_PTR head); //tree##### //BFS - Dreadth First Search //DFS - Depth First Search //Tree Traversals, Expression Tree //graph##### //BST - Binary Search Tree //AVL Tree //B Tree //Hashing #endif /* SRC_QSHAN_PRACTICE_H_ */ <file_sep>#!/bin/bash export MakeBuildLogFileName="fshan_cbuild_log.txt" #source try_clean # run like this #for gcc make #make clean #make all make all | tee -a ${MakeBuildLogFileName} #echo "BUILD_DIR is: " $BUILD_DIR #make #./build_gcc/test_main #make run #for cmake + make case #cd ./build #cmake -G "Unix Makefiles" .. #cmake .. #make #./Test_Hello <file_sep>#include <stdio.h> #include "arg_read.h" #include "string.h" //int arg_read(char *argv[], char *input_arg_list[][3][MAXSTRING_LENGTH]) int arg_read(int argc ,char *argv[] ,char input_arg_list[][3][MAX_STRING_LENGTH]) { int i, j;//for arg print control int value_returned=0; #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif #if 1 { //ToCheck /* #define MAX_STRING_LENGTH 100 char input_arg_list[][3][MAX_STRING_LENGTH]= { {"--port" ,"" ,"set port name info"} ,{"--file" ,"" ,"set file name"} ,{"--end--" ,"--end--" ,"reserved keywords"} }; */ printf("------------------------------\n"); if ((strcasecmp (argv[1], "--help") == 0)) { printf("##### Help arguments format:\n"); printf("##### --keyword key_value_need_input\n"); printf("##### keyword supported lists:\n"); for (j=0;;j++) { if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list[j][0] ,input_arg_list[j][2]); } //return 1 value_returned =1; } else { for(i=1;i<argc;) { //printf("------------------------------\n"); //printf("##### Check argv[%d] info: %s\n" ,i ,argv[i]); for (j=0;;j++) { //printf("##### Check input_arg_list[%d][0] info: %s\n" ,i ,input_arg_list[j][0]); if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} if ((strcasecmp (argv[i], input_arg_list[j][0]) == 0)) //if ((strcmp (argv[i], input_arg_list[j][0]) == 0)) { //printf("##### get input_arg_list[j][0] info: %s\n", argv[i+1]); //strcpy(input_arg_list[j][1], argv[i+1]); //TODO//strncpy(input_arg_list[j][1], argv[i+1] ,MAX_STRING_LENGTH); strncpy(input_arg_list[j][1], argv[i+1] ,strlen(argv[i+1])); printf("##### Get %s info: %s\n" ,input_arg_list[j][0] ,input_arg_list[j][1]); } } i=i+2; } //return 0 value_returned =0; } } #endif //return 0; return value_returned; } int print_arg_list(char input_arg_list[][3][MAX_STRING_LENGTH]) { int value_returned =0; int i=0; #if PRINT_DEBUG_ENABLE printf("--------------------------------------------------\n"); printf("Running the %s() in %s\n" ,__func__ ,__FILE__); printf("--------------------------------------------------\n"); #endif printf("------------------------------\n"); printf("check the input_arg_list info\n"); for (i=0;;i++) { if ((strcasecmp (input_arg_list[i][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list[i][0] ,input_arg_list[i][1]); } return value_returned; } <file_sep>#include <stdio.h> #include "say_hello_12.h" #include "test12_shared.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test12 \n"); printf("\n"); say_hello12(); printf("Try to call function_shared_test12(1), get: 0x%x \n" , function_shared_test12(1) ); printf("\n"); printf("Bye test12 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep># run like this #cmake -G "Unix Makefiles" .. cmake .. make clean make echo "please makesure the lib is in ../lib path" ./Test05_Hello <file_sep>#ifndef __SAY_HELLO_04_H__ #define __SAY_HELLO_04_H__ int say_hello04(); #endif<file_sep>#ifndef __TEST09_STRING_H__ #define __TEST09_STRING_H__ //data type definition here //variable definition here char *ustring_array_test09[]= /*pointer array, the element is point to constant string*/ { "00 This is contents of element of string array test09" , "01 This is contents of element of string array test09" , "02 This is contents of element of string array test09" , "03 This is contents of element of string array test09" , "04 This is contents of element of string array test09" , "05 This is contents of element of string array test09" , "06 This is contents of element of string array test09" , "07 This is contents of element of string array test09" , "08 This is contents of element of string array test09" , "09 This is contents of element of string array test09" , "10 This is contents of element of string array test09" , "11 This is contents of element of string array test09" }; //function declearation here int function01_test09(int arg0); int function02_test09(int arg0, int arg1); int function03_test09(int arg0, int arg1); int function04_d_var_test09(int arg0, ...); #endif <file_sep>###### # 指定 cmake 最低编译版本 CMAKE_MINIMUM_REQUIRED(VERSION 3.5) #Project Name #PROJECT (Test10_Hello) PROJECT (SayHello10) # add file list, SET(SRC_LIST tested01.c testates02.c) #SET(SRC_LIST ./src/test10.c) FILE(GLOB SRC_LIST "${PROJECT_SOURCE_DIR}/src/*.c") ###### 打印 SRC_LIST 文件列表 ###### MESSAGE(STATUS ${SRC_LIST}) #add the shared source code of the file path FILE(GLOB SRC_SHARED_LIST "${PROJECT_SOURCE_DIR}/src_shared/*.c") ###### MESSAGE(STATUS ${SRC_SHARED_LIST}) ###### 指定头文件目录 #####INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include) # include path INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include) # 指定输出 .so 动态库的目录位置 #SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/libShared) SET(LIBRARY_OUTPUT_PATH ./libShared) # 指定生成动态库 #ADD_LIBRARY(SayHello10 SHARED ${SRC_LIST}) ADD_LIBRARY(Test10Shared SHARED ${SRC_SHARED_LIST}) ###### 指定生成静态库 #####ADD_LIBRARY(SayHello10 ${SRC_LIST}) #print check the variable content in env # 输出打印构建目录 MESSAGE(STATUS "This is HELLO_BINARY_DIR " ${HELLO_BINARY_DIR}) # 输出打印资源目录 MESSAGE(STATUS "This is HELLO_SOURCE_DIR " ${HELLO_SOURCE_DIR}) # 输出打印资源目录,与HELLO_SOURCE_DIR 一样 MESSAGE(STATUS "This is PROJECT_SOURCE_DIR " ${PROJECT_SOURCE_DIR}) # 输出打印 CMake 资源目录,与 PROJECT_SOURCE_DIR 一样 MESSAGE(STATUS "This is CMAKE_SOURCE_DIR " ${CMAKE_SOURCE_DIR}) # 生成可执行文件 hello ,${SRC_LIST}是引用变量,也就是源文件 hello.cpp # gen ext file, list the dependancy file here ADD_EXECUTABLE(Test10_Hello ${SRC_LIST} ${SRC_SHARED_LIST}) <file_sep>###### # 指定 cmake 最低编译版本 CMAKE_MINIMUM_REQUIRED(VERSION 3.5) #Project Name #PROJECT (Test_Uart_Hello) #PROJECT (SayHello_Uart) #PROJECT (Test_Uart) PROJECT (test_uart VERSION 1.0) #------------------------------ #SET(OutputPathQshan build_cmake_cmake) #MAKE_DIRECTORY(${OutputPathQshan}) #SET(PROJECT_BINARY_DIR ${OutputPathQshan}) #set(CMAKE_BUILD_DIR ${OutputPathQshan}) #set(CMAKE_BINARY_DIR ${OutputPathQshan}) #------------------------------ SET(CMAKE_C_COMPILER clang) SET(CMAKE_CPP_COMPILER clang++) #set(CMAKE_C_COMPILER iccarm) #set(CMAKE_CPP_COMPILER iccarm) #------------------------------ #set here or set in the cmake argument in shell, one time is enough SET(CMAKE_BUILD_TYPE Debug) #SET(CMAKE_BUILD_TYPE RelWithDebInfo) #SET(CMAKE_BUILD_TYPE Release) #SET(CMAKE_BUILD_TYPE MinSizeRel) #SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb") #TODO#worked SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb -DPRINT_DEBUG_ENABLE=1") SET(CMAKE_C_FLAGS_DEBUG "$ENV{CFLAGS} -O0 -Wall -g2 -ggdb -DPRINT_DEBUG_ENABLE=1") SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall") #ADD_COMPILE_OPTIONS(-Wall -g) #------------------------------ SET(CMAKE_CXX_STANDARD 11) SET(CMAKE_CXX_STANDARD_REQUIRED True) #------------------------------ # add file list, SET(SRC_LIST tested02.c testates02.c) #FILE(GLOB SRC_LIST "${PROJECT_SOURCE_DIR}/src/*.c" "${PROJECT_SOURCE_DIR}/src/*.cpp" "${PROJECT_SOURCE_DIR}/src/*.s ${PROJECT_SOURCE_DIR}/libs/*/src/*.c" "${PROJECT_SOURCE_DIR}/libs/*src/*.cpp" "${PROJECT_SOURCE_DIR}/libs/*src/*.s") FILE(GLOB SRC_LIST "${PROJECT_SOURCE_DIR}/test/src/*.c" "${PROJECT_SOURCE_DIR}/test/src/*.cpp" "${PROJECT_SOURCE_DIR}/test/src/*.s" "${PROJECT_SOURCE_DIR}/libs/*/src/*.c" "${PROJECT_SOURCE_DIR}/libs/*/src/*.cpp" "${PROJECT_SOURCE_DIR}/libs/*/src/*.s") ###### print SRC_LIST for debug ##### MESSAGE(STATUS ${SRC_LIST}) #add the shared source code of the file path FILE(GLOB SRC_SHARED_LIST # "${PROJECT_SOURCE_DIR}/libs/shared/src/*.c" # "${PROJECT_SOURCE_DIR}/libs/shared/src/*.cpp" # "${PROJECT_SOURCE_DIR}/libs/shared/src/*.s") "${PROJECT_SOURCE_DIR}/libs_shared/*/src/*.c" "${PROJECT_SOURCE_DIR}/libs_shared/*/src/*.cpp" "${PROJECT_SOURCE_DIR}/libs_shared/*/src/*.s") ###### MESSAGE(STATUS ${SRC_SHARED_LIST}) # include path for project #INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/libs/*/header) INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/test/header # ${PROJECT_SOURCE_DIR}/libs/practice/header # ${PROJECT_SOURCE_DIR}/libs/*/header ${PROJECT_SOURCE_DIR}/libs/uart/header ${PROJECT_SOURCE_DIR}/libs/file_log/header ${PROJECT_SOURCE_DIR}/libs/time_stamp_log/header ${PROJECT_SOURCE_DIR}/libs/say_hello/header ) # include path for shared INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/libs_shared/shared/header #${PROJECT_SOURCE_DIR}/libs_shared/*/header ) # 指定输出 .so 动态库的目录位置 #SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/libShared) SET(LIBRARY_OUTPUT_PATH ./libShared) # 指定生成动态库 #ADD_LIBRARY(SayHelloUart SHARED ${SRC_LIST}) ADD_LIBRARY(TestUartShared SHARED ${SRC_SHARED_LIST}) #ADD_LIBRARY(TestUartShared STATIC ${SRC_SHARED_LIST}) #ADD_LIBRARY(TestUartShared MODULE ${SRC_SHARED_LIST}) #TARGET_INCLUDE_DIRECTORIES(TestUartShared PRIVATE ${PROJECT_SOURCE_DIR}/libs/shared/header) #TARGET_INCLUDE_DIRECTORIES(TestUartShared PUBLIC ${PROJECT_SOURCE_DIR}/libs/shared/header) ###### 指定生成静态库 #####ADD_LIBRARY(SayHelloUart ${SRC_LIST}) #print check the variable content in env MESSAGE(STATUS "------------------------------------------------------------") MESSAGE(STATUS "Check/confirm variable the status") MESSAGE(STATUS "{PROJECT} " ${PROJECT}) MESSAGE(STATUS "{PROJECT_NAME} " ${PROJECT_NAME}) MESSAGE(STATUS "{PROJECT_VERSION} " ${PROJECT_VERSION}) MESSAGE(STATUS "{CMAKE_PROJECT_NAME} " ${CMAKE_PROJECT_NAME}) #------------------------------ MESSAGE(STATUS "{HELLO_SOURCE_DIR} " ${HELLO_SOURCE_DIR}) #------------------------------ MESSAGE(STATUS "{PROJECT_BINARY_DIR} " ${PROJECT_BINARY_DIR}) MESSAGE(STATUS "{PROJECT_SOURCE_DIR} " ${PROJECT_SOURCE_DIR}) #------------------------------ MESSAGE(STATUS "{CMAKE_BINARY_DIR} " ${CMAKE_BINARY_DIR}) MESSAGE(STATUS "{CMAKE_SOURCE_DIR} " ${CMAKE_SOURCE_DIR}) MESSAGE(STATUS "{CMAKE_BUILD_TOOL} " ${CMAKE_BUILD_TOOL}) #------------------------------ MESSAGE(STATUS "{CMAKE_C_COMPILER} " ${CMAKE_C_COMPILER}) MESSAGE(STATUS "{CMAKE_CPP_COMPILER} " ${CMAKE_CPP_COMPILER}) #------------------------------ MESSAGE(STATUS "{CXXFLAGS} " ${CXXFLAGS}) MESSAGE(STATUS "{CMAKE_CXX_FLAGS_DEBUG} " ${CMAKE_CXX_FLAGS_DEBUG}) MESSAGE(STATUS "{CMAKE_C_FLAGS_DEBUG} " ${CMAKE_C_FLAGS_DEBUG}) MESSAGE(STATUS "{CXX_FLAGS_RELEASE} " ${CXX_FLAGS_RELEASE}) MESSAGE(STATUS "------------------------------------------------------------") #------------------------------ # 生成可执行文件 hello ,${SRC_LIST}是引用变量,也就是源文件 hello.cpp # gen ext file, list the dependancy file here #ADD_EXECUTABLE("${PROJECT_NAME}" ${SRC_LIST} ${SRC_SHARED_LIST}) ADD_EXECUTABLE( # Test_Uart ${PROJECT_NAME} ${SRC_LIST} ${SRC_SHARED_LIST}) <file_sep>#include <stdio.h> #include "say_hello_11.h" #include "test11_shared.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test11 \n"); printf("\n"); say_hello11(); printf("Try to call function_shared_test11(1), get: 0x%x \n" , function_shared_test11(1) ); printf("\n"); printf("Bye test11 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#!/bin/bash # run like this export TestBuildPath="./build_cmake2" if [ ! -d ${TestBuildPath} ]; then mkdir -p ${TestBuildPath} fi if [ -d ${TestBuildPath} ]; then cd ${TestBuildPath} #cmake -G "Unix Makefiles" .. cmake .. make clean make # ./Test_Hello ./test_run cd - # mkdir build_cmake fi <file_sep>#include <stdio.h> #include "test_main.h" //#include "say_hello_.h" //#include "test_shared.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test \n"); printf("\n"); say_hello(); printf("Try to call function_shared_test(1), get: 0x%x \n" , function_shared_test(1) ); printf("\n"); printf("Bye test \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#good doc #https://scons.org/doc/production/HTML/scons-user.html#app-functions #Library('',[]) #Library('TestSharedLib', ['../src_shared/test_shared.c']) #Library('TestSharedLib', ['../src_shared/test_shared.c'] ,CPPPATH=['../include']) #Program('',[]) #Program('',[]) #Program('test' ,['../src/test.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_.c'] ,LIBS=['TestSharedLib'] ,LIBPATH=['.']) #Program('test' ,['../src/test.c' ,'../src/say_hello_.c'] ,CPPPATH=['../include'] ,LIBS=['TestSharedLib'] ,LIBPATH=['.']) #Program('test' ,['../src/test.c' ,'../src/say_hello_.c'] ,CPPPATH=['../include'] ,LIBS=['TestSharedLib'] ,LIBPATH=['.']) #SConstruct #env = Environment(CC='gcc' ,CCFLAGS=' -O2 -Wall -g' ,CPPDEFINES=['MyDefine02']) # #env = Environment(CC='gcc') #env = Environment(CXX='g++') env = Environment(CC='clang') #env = Environment(CXX='clang++') env.Append(CXX='clang++') # #env.BuildDir('buildpath' ,'src') # #env.Append(CCFLAGS=' -Wall -g') #env.Append(CCFLAGS=' -O2 -Wall -g') env.Append(CCFLAGS=' -O2 -Wall -g') env.Append(CFLAGS=' -O2 -Wall -g') # #TODO#worked env.Append(CCFLAGS=' -DPRINT_DEBUG_ENABLE=1') env.Append(CFLAGS=' -DPRINT_DEBUG_ENABLE=1') # env.Replace(CC='clang') env.Replace(CXX='clang++') # env.Prepend(CPPDEFINES=['MyFirstDefine00']) env.Append(CPPDEFINES=['MyDefine02']) env.Append(MyVariableAdded01=['MyVariableAdded01']) print("MyVariableAdded01 = %s" % env['MyVariableAdded01']) # opt = env.Clone(CCFLAGS=[' -O2']) opt = env.Clone(CFLAGS=[' -O2']) dbg = env.Clone(CCFLAGS=[' -Wall -g']) dbg = env.Clone(CFLAGS=[' -Wall -g']) # #o = opt.Object('test-o' ,['foo.c']) #opt.Program(o) ## #d = dbg.Object('test-d' ,['foo.c']) #dbg.Program(d) Export ('env') #Export ("opt", "dbg") #Export ('opt dbg') Export ('opt', 'dbg') #Export ('dbg') #check the env setting here print("[env.CC] is %s" % env['CC']) print("[env.CXX] is %s" % env['CXX']) print("[env.CCFLAGS] is %s" % env['CCFLAGS']) print("[env.CFLAGS] is %s" % env['CFLAGS']) objs = [] header_file_path = [] # , variant_dir='build_sc' #objs.append( SConscript([Glob('./libs/*/SConscript')] , exports='env') ) objs.append( SConscript(['./test_main/SConscript'] , exports='env') ) objs.append( SConscript(['./libs_shared/shared/SConscript'] , exports='env') ) objs.append( SConscript(['./libs/say_hello/SConscript'] , exports='env') ) #objs.append( SConscript(['./libs/practice/SConscript'] , exports='env') ) #not_work#print (env.File('SConscript' ,['./libs' ,'./libs_shared'])) #not_work# #not_work#try_get_file[] = env.FindFile('SConscript' ,['./libs' ,'./libs_shared']) #not_work#try_get_file[] = #objs.append(env.FindFile('SConscript', ['./libs', './libs_shared'])) #print("[get_data_after_findfile] is %s" % get_data_after_findfile[]) #not_work#print (try_get_file[]) env.Program('test_run' ,objs ,CPPPATH=[ # './test_main/header' # , './libs_shared/shared/header' # , './libs/say_hello/header' ]) # ,'./libs/practice/header' <file_sep>#!/bin/bash # run like this export Test14BuildPath="./build_cmake" export Test14SourcePath="." #cmake3.14#cmake -B${Test14BuildPath} -S${Test14SourcePath} cmake -B${Test14BuildPath} -H${Test14SourcePath} cd ${Test14BuildPath} make clean make # ./Test14 arg1 arg2 arg3 arg4 arg5 arg6 # ./Test14 arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 ./test14 arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 --File /home/data/outputdata.txt cd - <file_sep>#ifndef __TEST14_H__ #define __TEST14_H__ #include "test_setting.h" #ifndef PRINT_DEBUG_ENABLE #define PRINT_DEBUG_ENABLE 1 #endif #include "test14_shared.h" #include "say_hello_14.h" #include "arg_read.h" #include "string.h" #endif <file_sep>#include <stdio.h> int say_hello03() { printf("hi, test03 \n"); return 0; } <file_sep>#include <stdio.h> int say_hello14() { printf("hi, test14 \n"); return 0; } <file_sep>#!/bin/bash # run like this export TestUartBuildPath="./build_cmake" export TestUartSourcePath="." #cmake3._uart#cmake -B${Test_uartBuildPath} -S${Test_uartSourcePath} cmake -B${TestUartBuildPath} -H${TestUartSourcePath} cd ${TestUartBuildPath} make clean make ./test_uart cd - <file_sep>#ifndef __SAY_HELLO_06_H__ #define __SAY_HELLO_06_H__ int say_hello06(); #endif <file_sep>#include <stdio.h> #include "time_stamp_log.h" //#include <time.h> /* time - run programs and summarize system resource usage */ //struct timespec start_time[], last_stat[], last_timeout[], last_read[], last_write[]; struct timespec current; struct timespec start_time, last_stat, last_timeout, last_read, last_write; //get the current time//clock_gettime(CLOCK_MONOTONIC, &current); int init_time_stamp_log() { //struct timespec current; //struct timespec start_time, last_stat, last_timeout, last_read, last_write; clock_gettime(CLOCK_MONOTONIC, &current); start_time = current; last_stat = current; last_timeout = current; last_read = current; last_write = current; return 0; } int diff_ms(const struct timespec *t1, const struct timespec *t2) { //ToCheck struct timespec diff; ///* POSIX.1b structure for a time value. This is like a `struct timeval' but // has nanoseconds instead of microseconds. */ //struct timespec // { // __time_t tv_sec; /* Seconds. */ // __syscall_slong_t tv_nsec; /* Nanoseconds. */ // }; //clock_gettime(CLOCK_MONOTONIC, &current); diff.tv_sec = t1->tv_sec - t2->tv_sec; diff.tv_nsec = t1->tv_nsec - t2->tv_nsec; if (diff.tv_nsec < 0) { diff.tv_sec--; diff.tv_nsec += 1000000000; } //the unit is second return (diff.tv_sec * 1000 + diff.tv_nsec/1000000); } int check_time_stamp_log_data() { //struct timespec current; //struct timespec start_time, last_stat, last_timeout, last_read, last_write; clock_gettime(CLOCK_MONOTONIC, &current); //start_time = current; //last_stat = current; //last_timeout = current; //last_read = current; //last_write = current; printf("start_time diff is %.1fs.\n", (double)diff_ms(&current, &start_time ) / 1000); printf("last_stat diff is %.1fs.\n", (double)diff_ms(&current, &last_stat ) / 1000); printf("last_timeout diff is %.1fs.\n", (double)diff_ms(&current, &last_timeout ) / 1000); printf("last_read diff is %.1fs.\n", (double)diff_ms(&current, &last_read ) / 1000); printf("last_write diff is %.1fs.\n", (double)diff_ms(&current, &last_write ) / 1000); return 0; } <file_sep>#ifndef __TEST12_SHARED_H__ #define __TEST12_SHARED_H__ int function_shared_test12(int arg0); #endif <file_sep>#include "file_log.h" FILE *p_fp_global; char *p_file_name[MAX_NUMBER_FILENAME]; #if 1 //file operation files #include <stdio.h> int file_init_func(char *p_file_name[MAX_NUMBER_FILENAME]) { #if PRINT_DEBUG_ENABLE printf("Run in %s\n" ,__func__); #endif //return the file handler //p_fp = fopen(p_file_name, "a+"); //p_fp = fopen("test_uart_file_test.txt", "a+"); p_fp_global = fopen(*p_file_name, "a+"); //fclose(p_fp); fclose(p_fp_global); //p_fp_global = fopen(*p_file_name, "r+"); //p_fp_global = fopen(*p_file_name, "r"); //return *p_fp; return 0; } //int file_write_func(FILE *p_fp ,char argv[]) int file_write_func(char argv[MAX_NUMBER_PER_LINE]) { #if PRINT_DEBUG_ENABLE printf("Run in %s\n" ,__func__); #endif //file write case //open, write and close //char argv[] = "Try to write file test from test_uart.c file!\n"; //char argv[] = "Try to write file test from test_uart.c file!"; //argv = "Try to write file test from test_uart.c file!"; #if PRINT_DEBUG_ENABLE //printf("the write contents is %s\n" ,argv); printf("The write contents is \"%s\" in %s\n" ,argv ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("Try #####fwrite() function in %s\n" ,__func__); #endif #if PRINT_DEBUG_ENABLE printf("Try #####fwrite() function in %s\n" ,__func__); #endif p_fp_global = fopen(*p_file_name, "a+"); #if PRINT_DEBUG_ENABLE printf("Try #####fprintf() function in %s\n" ,__func__); #endif //fprintf(p_fp ,"fprintf %s\n" ,argv); fprintf(p_fp_global ,"fprintf %s\n" ,argv); //fclose(p_fp); fclose(p_fp_global); return 0; } int file_read_by_line_func(FILE *p_fp ) { //file read case char *line_buf = NULL; int line_count = 0; #if PRINT_DEBUG_ENABLE printf("Run in %s\n" ,__func__); #endif //p_fp = p_fp_global; //p_fp_global = fopen(*p_file_name, "r+"); p_fp_global = fopen(*p_file_name, "r"); #if PRINT_DEBUG_ENABLE //printf("Try to open file %s\n\r" ,p_file_name); printf("Try to open file %s\n" ,*p_file_name); #endif //fgetc() - Used to read single character from file. //fgets() - Used to read string from file. //fscanf() - Use this to read formatted input from file. //fread() - Read block of raw bytes from file. Used to read binary files. #if 1 //p_fp = fopen(*p_file_name, "r+"); #if PRINT_DEBUG_ENABLE printf("Try #####getline() function in %s\n" ,__func__); #endif size_t line_buf_size = 0; ssize_t line_size; #if PRINT_DEBUG_ENABLE printf("Get p_fp is 0x%x in %s\n" ,(unsigned int)p_fp ,__func__); printf("Get p_fp_global is 0x%x in %s\n" ,(unsigned int)p_fp_global ,__func__); #endif /* Get the first line of the file. */ //line_size = getline(&line_buf, &line_buf_size, p_fp); line_size = getline(&line_buf, &line_buf_size ,p_fp_global); line_count = 0; /* Loop through until we are done with the file. */ while (line_size >= 0) { /* Increment our line count */ line_count++; #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("line[%06d]: chars=%06zd, buf size=%06zu, contents: %s\n" ,line_count ,line_size ,line_buf_size ,line_buf); #endif /* Get the next line */ line_size = getline(&line_buf ,&line_buf_size ,p_fp); } #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("The total lines is %d\n" ,line_count); #endif fclose(p_fp); #endif //not worked #if 0 //p_fp = fopen(*p_file_name, "r+"); p_fp_global = fopen(*p_file_name, "r"); #if PRINT_DEBUG_ENABLE printf("Try #####fscanf() function in %s\n" ,__func__); #endif //char line_data[128] = {0}; char line_data[MAX_NUMBER_PER_LINE] = {0}; //while (fscanf(p_fp, "%[^\n]", line_data) != EOF) while (fscanf(p_fp_global, "%[^\n]" ,line_data) != EOF) { printf("> %s\n", line_data); } fclose(p_fp_global); #endif //fgetc() - Used to read single character from file. //fgets() - Used to read string from file. //fgets reads in size - 1 characters from the stream and stores it into *s pointer. The string is automatically null-terminated. fgets stops reading in characters if it reaches an EOF or newline. //fscanf() - Use this to read formatted input from file. //fread() - Read block of raw bytes from file. Used to read binary files. //worked for txt format with end of line char #if 0 //p_fp = fopen(p_file_name, "r+"); p_fp = fopen(p_file_name, "r"); #if PRINT_DEBUG_ENABLE printf("Try #####fgets() function in %s\n" ,__func__); #endif //char *path; //char line[MAX_LINE_LENGTH] = {0}; //char line[128] = {0}; char line[MAX_NUMBER_PER_LINE] = {0}; //char line[128]; //unsigned int line_count = 0; line_count = 0; /* Get each line until there are none left */ //while (fgets(line, MAX_LINE_LENGTH, file)) while (fgets(line, 128, p_fp)) { /* Print each line */ printf("line[%06d]: %s", ++line_count, line); /* Add a trailing newline to lines that don't already have one */ if (line[strlen(line) - 1] != '\n') { printf("\n"); } } #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("The total lines is %d\n" ,line_count); #endif fclose(p_fp); #endif return 0; } #endif<file_sep>#!/bin/bash # run like this if [ ! -d ./build_cmake ]; then mkdir build_cmake fi if [ -d ./build_cmake ]; then cd build_cmake #cmake -G "Unix Makefiles" .. #cmake .. cmake -DCMAKE_BUILD_TYPE=Debug .. #cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .. #cmake -DCMAKE_BUILD_TYPE=Release .. make clean make ./Test08_Hello cd - # mkdir build_cmake fi <file_sep>#include <stdio.h> int say_hello04() { printf("hi, test04 \n"); return 0; }<file_sep># run like this #for gcc make make clean make make run #for cmake + make case #cd ./build ##cmake -G "Unix Makefiles" .. #cmake .. #make #./Test06_Hello <file_sep># # #meaning of specific strings #*# $@ all of FileNameWithExtension produced # $* all of FileNameWithoutExtension produced # $< the FileName of first dependance item #*# $^ the dependance items with space islated and remove the repeated item # $+ the dependance items with space islated, but do not remove the repeated item # $? the dependance items with space islated, but just have the new item # % # #automatic variables descriptions # $@ The file name of the target # $< The name of the first prerequisite # $^ The names of all the prerequisites # $+ prerequisites listed more than once are duplicated in the order # # define a variable, Var=xx , and the methods of using variable is $(Var) # #search path # VPATH = src include # vpath %.c src # vpath %.h include # #match standard # %.o: %.c # # %.o: %.c # gcc -g -o $@ -c $< # #update_content#CC=gcc #update_content#CFLAGS = -I ./include #update_content#DEPS = say_hello_09.h #update_content# #update_content#TARGET=test09 #update_content# #update_content##all: test09 #update_content#all: $(TARGET) #update_content# #update_content##test09 : ./src/say_hello_09.c ./src/test09.c #update_content#$(TARGET): ./src/say_hello_09.c ./src/test09.c #update_content# $(CC) -g -o $@ $^ $(CFLAGS) #update_content## $(CC) -o test09 ./src/say_hello_09.c ./src/test09.c $(CFLAGS) #update_content## gcc -o test09 ./src/say_hello_09.c ./src/test09.c -I ./include #update_content# #update_content#clean: #update_content## rm test09 #update_content# rm $(TARGET) #.PHONY: all #CC=gcc CC=clang TARGET_EXEC ?= test09 BUILD_DIR ?= ./build_gcc SRC_DIRS ?= ./src BUILD_LOG_FILE ?= $(BUILD_DIR)/$(TARGET_EXEC).log #$(BUILD_LOG_FILE): # $(MKDIR_P) $(BUILD_DIR) # touch $(BUILD_DIR)/$(TARGET_EXEC).log #all: $(TARGET_EXEC) #source code info #SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c -or -name *.s) SRCS := $(shell find $(SRC_DIRS) -name *.c -or -name *.s) OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) DEPS := $(OBJS:.o=.d) #include/HeadhFile path info INC_DIRS := $(shell find $(SRC_DIRS) -type d) INC_DIRS += ./include INC_FLAGS := $(addprefix -I,$(INC_DIRS)) CPPFLAGS ?= $(INC_FLAGS) -MMD -MP #DEBFLAGS ?= -O2 -g DEBFLAGS ?= -O -g # "-O" is needed to expand inlines #DEBFLAGS ?= -O -g -DSCULL_DEBUG # "-O" is needed to expand inlines $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(CC) $(OBJS) -o $@ $(LDFLAGS) # assembly $(BUILD_DIR)/%.s.o: %.s $(MKDIR_P) $(dir $@) $(AS) $(ASFLAGS) -c $< -o $@ # c source $(BUILD_DIR)/%.c.o: %.c $(MKDIR_P) $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ # c++ source $(BUILD_DIR)/%.cpp.o: %.cpp $(MKDIR_P) $(dir $@) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ run: $(BUILD_DIR)/$(TARGET_EXEC) all : clean #.PHONY: clean clean: $(RM) -r $(BUILD_DIR) -include $(DEPS) MKDIR_P ?= mkdir -p <file_sep>#ifndef __TEST13_SHARED_H__ #define __TEST13_SHARED_H__ int function_shared_test13(int arg0); #endif <file_sep>#include <stdio.h> int say_hello08() { printf("-------------------- \n"); printf("hi, test08 \n"); return 0; } <file_sep>#include <stdio.h> #include "say_hello_07.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test07 \n"); printf("\n"); say_hello07(); unsigned int udata1, udata2, udata3; unsigned int uresult1, uresult2, uresult3; udata1 = 0x0; udata2 = 0x11; udata3 = 0x11; uresult1 = udata1 ^ udata2; printf("hi, udata1 ^ udata2 = 0x%x \n", uresult1); uresult2 = udata2 ^ udata3; printf("hi, udata2 ^ (udata3) = 0x%x \n", uresult2); uresult3 = udata2 ^ udata1; printf("hi, udata3 ^ udata1 = 0x%x \n", uresult3); printf("\n"); printf("Bye test07 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#include <stdio.h> #include "say_hello_06.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test06 \n"); printf("\n"); say_hello06(); //the contents of main function here printf("The function contents stat run \n"); printf("\n"); printf("Bye test06 \n"); printf("===================================================\n"); return 0; } <file_sep>#ifndef __UART_H__ #define __UART_H__ #ifndef PRINT_DEBUG_ENABLE #define PRINT_DEBUG_ENABLE 1 #endif int uart_api(); int uart_init(); #include <stdio.h> #include <stdlib.h> /* */ #include <unistd.h> /* UNIX Standard Definitions */ #include <termios.h> /* POSIX Terminal Control Definitions */ #include <sys/file.h> /* */ #include <fcntl.h> /* File Control Definitions */ #include <sys/ioctl.h> /* ioctl - control device */ #include <linux/serial.h> /* */ #include <errno.h> /* ERROR Number Definitions */ #include <sys/types.h> /* */ #include <sys/stat.h> /* stat - display file or file system status */ #include <strings.h> /* strings - print the strings of printable characters in files */ #include <string.h> /* string operations */ #include <poll.h> /* poll, ppoll - wait for some event on a file descriptor */ // #include <time.h> //UART decode format //bit[7:0] is from sw view, remove the start and end of serial package // //bit[3:0] -> 1:csr ,2:spi ,3:efuse // //bit[4] -> 0:wirte ,1:read //bit[7:4] -> 0/2/3/5/(6+end):wirte ,1/4/(7+end):read //read 32 bit addr, 32 bit data #define CMD_CODE_READ 0x11 #define CMD_READ_PACKAGE_LEN 0x5 //#define CMD_READ_PACKAGE_LEN 0x1024 //write 32 bit addr, 32 bit data #define CMD_CODE_WRITE 0x01 #define CMD_WRITE_PACKAGE_LEN 0x9 //read 16 bit addr, 8 bit data #define CMD_CODE_READ16 0x13 #define CMD_READ16_PACKAGE_LEN 0x3 //write 16 bit addr, 8 bit data #define CMD_CODE_WRITE16 0x03 #define CMD_WRITE16_PACKAGE_LEN 0x4 //#define BUFFER_RECEIVED_SIZE 1024 #define BUFFER_RECEIVED_SIZE 200 //for returned hander of serial port open extern int _fd; //for the port name on pc hardware view, like"/dev/ttyUSB0" extern char *_cl_port; int setup_serial_port_01(char port_name[], int serial_speed); unsigned int write_out_hex_with_reorder_01(int addr ,int data); unsigned int read_in_hex_with_reorder_01(int addr); unsigned int poll_data_one_time_without_while_01(); unsigned int or_write_register(int addr ,int data); unsigned int ir_read_register(int addr); void exit_handler(); int setup_serial_port(char port_name[], int serial_speed); void clear_custom_speed_flag(); int write_hello_string(); unsigned int write_order_hex(); unsigned int write_out_hex_with_reorder(int addr ,int data); unsigned int read_one_time_string(); unsigned int read_in_hex_with_reorder(int addr); unsigned int poll_data_one_time_without_while(); unsigned int read_in_hex_with_reorder(int addr); #endif <file_sep>#!/bin/bash # run like this #for gcc make #make clean make all #make #./build_gcc/test14 #for cmake + make case #cd ./build #cmake -G "Unix Makefiles" .. #cmake .. #make #./Test14_Hello <file_sep>#Library('',[]) #Library('Test12SharedLib', ['../src_shared/test12_shared.c']) #Library('Test12SharedLib', ['../src_shared/test12_shared.c'] ,CPPPATH=['../include']) #Program('',[]) #Program('test12' ,['../src/test12.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_12.c'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['../src/test12.c' ,'../src/say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['test12.c' ,'say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) #Program('test12' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) #Import('env') #Import('opt') #Import('dbg') #Import ('BuildOutputFilePath') Import ('*') # #env.Program('test12' ,Glob('*.c') ,CPPPATH=['../../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../BuildOutputFilePath/build_sc_shared']) #env.Program('test12' ,Glob('*.c') ,CPPPATH=['../../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../build_sc_shared']) #env.Program('test12' ,Glob('*.c') ,CPPPATH=['../../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../' + BuildOutputFilePath + '/build_sc_shared']) #env.Program('test12' ,Glob('*.c') ,CPPPATH=['../../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../build_sc_shared']) env.Program('test12' ,Glob('*.c') ,CPPPATH=['../../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) #env.Program('test12' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) #opt.Program('test12-opt' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) #dbg.Program('test12-dbg' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['../src_shared']) <file_sep>#ifndef __TEST_UART_H__ #define __TEST_UART_H__ #include "test_uart_shared.h" #include "say_hello_uart.h" #include "uart.h" #include "time_stamp_log.h" #include "file_log.h" //#include "test_uart.h" #ifndef PRINT_DEBUG_ENABLE #define PRINT_DEBUG_ENABLE 1 #endif #endif <file_sep>#include <stdio.h> #include <string.h> #include <stdarg.h> /*for va_list*/ #include "say_hello_09.h" #include "test09.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test09 \n"); printf("\n"); say_hello09(); int (*p2f_1a) (int); /*define a pointer point to a function*/ int (*p2f_2a[5]) (int, int); /*define a array of pointer point to a function with two arguments*/ //p2f_1a = function01_test09; p2f_1a = &function01_test09; p2f_2a[0] = &function02_test09; p2f_2a[1] = &function03_test09; printf("Try run p2f_1a, get result: 0x%x\n", p2f_1a(5)); printf("Try run p2f_2a[0], get result: 0x%x\n", p2f_2a[0](5, 1)); printf("Try run p2f_2a[1], get result: 0x%x\n", p2f_2a[1](5, 2)); printf("Try run function04_d_var_test09(1, 1), get result: 0x%x\n", function04_d_var_test09(1, 1)); printf("Try run function04_d_var_test09(2 ,1 ,1), get result: 0x%x\n", function04_d_var_test09(2 ,1 ,1)); printf("Try run function04_d_var_test09(3 ,1 ,1 ,1), get result: 0x%x\n", function04_d_var_test09(3 ,1 ,1 ,1)); printf("\n"); printf("Bye test09 \n"); printf("===================================================\n"); printf("\n"); return 0; } int function01_test09(int arg0) { printf("-------------------------------------------------- \n"); printf("Run the %s\n", __func__); printf("The arg0 0x%x\n", arg0); printf("Exit the %s\n", __func__); printf("-------------------------------------------------- \n"); return (arg0+1); } int function02_test09(int arg0, int arg1) { printf("-------------------------------------------------- \n"); printf("Run the %s\n", __func__); printf("The arg0 0x%x\n", arg0); printf("The arg1 0x%x\n", arg1); printf("Exit the %s\n", __func__); printf("-------------------------------------------------- \n"); return (arg0 + arg1 + 1); } int function03_test09(int arg0, int arg1) { printf("-------------------------------------------------- \n"); printf("Run the %s\n", __func__); printf("The arg0 0x%x\n", arg0); printf("The arg1 0x%x\n", arg1); printf("Exit the %s\n", __func__); printf("-------------------------------------------------- \n"); return (arg0 + arg1 + 1); } /* Macros Defined in header <stdarg.h> va_start enables access to variadic function arguments (function macro) va_arg accesses the next variadic function argument (function macro) va_copy (C99) makes a copy of the variadic function arguments (function macro) va_end ends traversal of the variadic function arguments (function macro) Type va_list holds the information needed by va_start, va_arg, va_end, and va_copy (typedef) typedef void *va_list; #define va_arg(ap,type) (*((type *)(ap))++) //获取指针ap指向的值,然后ap=ap+1,即ap指向下一个值, 其中<u>type</u>是 变参数的类型,可以是char(cter), int(eger), float等。 #define va_start(ap,lastfix) (ap=…) #define va_end(ap) // 清理/cleanup 指针ap in linux #define va_start(v,l) __builtin_va_start(v,l) #define va_end(v) __builtin_va_end(v) #define va_arg(v,l) __builtin_va_arg(v,l) #define va_copy(d,s) __builtin_va_copy(d,s) */ int function04_d_var_test09(int arg0, ...) { /*add arguments as a example*/ printf("-------------------------------------------------- \n"); printf("Run the %s\n", __func__); printf("The arg0 0x%x\n", arg0); int i; int sum =0; va_list argptr; /*void va_start(va_list argptr, lastparam);*/ va_start (argptr, arg0); //for(i=0;i<arg0;++i) for(i=0;i<arg0;i++) { /*type va_arg(va_list argptr, type);*/ sum += va_arg(argptr, int); } /*void va_end(va_list argptr);*/ va_end(argptr); printf("Exit the %s\n", __func__); printf("-------------------------------------------------- \n"); return sum; }<file_sep>#good doc #https://scons.org/doc/production/HTML/scons-user.html#app-functions #Library('',[]) #Library('Test11SharedLib', ['../src_shared/test11_shared.c']) #Library('Test11SharedLib', ['../src_shared/test11_shared.c'] ,CPPPATH=['../include']) #Program('',[]) #Program('',[]) #Program('test11' ,['../src/test11.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_11.c'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['../src/test11.c' ,'../src/say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['../src/test11.c' ,'../src/say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #SConstruct #env = Environment(CC='gcc' ,CCFLAGS=' -O2 -Wall -g' ,CPPDEFINES=['MyDefine01']) # env = Environment(CC='gcc') env.Replace(CC='clang') #env.Append(CCFLAGS=' -Wall -g') env.Append(CCFLAGS=' -O2 -Wall -g') # env.Prepend(CPPDEFINES=['MyFirstDefine00']) env.Append(CPPDEFINES=['MyDefine02']) env.Append(MyVariableAdded01=['MyVariableAdded01']) print("MyVariableAdded01 = %s" % env['MyVariableAdded01']) # opt = env.Clone(CCFLAGS=[' -O2']) dbg = env.Clone(CCFLAGS=[' -Wall -g']) # #env.Program('test11' ,['foo.c']) # #o = opt.Object('test11-o' ,['foo.c']) #opt.Program(o) ## #d = dbg.Object('test11-d' ,['foo.c']) #dbg.Program(d) Export ('env') #Export ("opt", "dbg") #Export ('opt dbg') Export ('opt', 'dbg') #Export ('dbg') #check the env setting here print("[env.CC] is %s" % env['CC']) print("[env.CXX] is %s" % env['CXX']) print("[env.CCFLAGS] is %s" % env['CCFLAGS']) #SConscript(['src_shared/SConscript'] # , variant_dir='build_sc_shared' # , duplicate=False # ) #SConscript(['src/SConscript'] # , variant_dir='build_sc' # , duplicate=False # ) SConscript(['src_shared/SConscript'] # , variant_dir='build_sc_shared' ) SConscript(['src/SConscript'] # , variant_dir='build_sc' ) <file_sep>#include <stdio.h> int say_hello07() { printf("hi, test07 \n"); return 0; } <file_sep>#!/bin/bash # scons -c #scons #scons --tree=all scons --tree=status #TODO#scons ./test_run #scons -c <file_sep># # # detail here: https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables #meaning of specific strings #*# $@ all of FileNameWithExtension produced # $* all of FileNameWithoutExtension produced # $< the FileName of first dependance item #*# $^ the dependance items with space islated and remove the repeated item # $+ the dependance items with space islated, but do not remove the repeated item # $? the dependance items with space islated, but just have the new item # $| The names of all the order-only prerequisites, with spaces between them. # % # #automatic variables descriptions # $@ The file name of the target # $< The name of the first prerequisite # $^ The names of all the prerequisites # $+ prerequisites listed more than once are duplicated in the order # # define a variable, Var=xx , and the methods of using variable is $(Var) # #search path # VPATH = src include # vpath %.c src # vpath %.h include # #match standard # %.o: %.c # # %.o: %.c # gcc -g -o $@ -c $< # #update_content#CC=gcc #update_content#CFLAGS = -I ./include #update_content#DEPS = say_hello_12.h #update_content# #update_content#TARGET=test12 #update_content# #update_content##all: test12 #update_content#all: $(TARGET) #update_content# #update_content##test12 : ./src/say_hello_12.c ./src/test12.c #update_content#$(TARGET): ./src/say_hello_12.c ./src/test12.c #update_content# $(CC) -g -o $@ $^ $(CFLAGS) #update_content## $(CC) -o test12 ./src/say_hello_12.c ./src/test12.c $(CFLAGS) #update_content## gcc -o test12 ./src/say_hello_12.c ./src/test12.c -I ./include #update_content# #update_content#clean: #update_content## rm test12 #update_content# rm $(TARGET) #.PHONY: all #CC=gcc CC=clang TARGET_EXEC ?= test12 BUILD_DIR ?= ./build_make SRC_DIRS ?= ./src #log define BUILD_LOG_FILE ?= $(BUILD_DIR)/$(TARGET_EXEC).log #share lib name defined TOP_OBJ_SHARED ?= Test12SharedLib.o #$(BUILD_LOG_FILE): # $(MKDIR_P) $(BUILD_DIR) # touch $(BUILD_DIR)/$(TARGET_EXEC).log #all: $(TARGET_EXEC) #source code info #SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c -or -name *.s) SRCS := $(shell find $(SRC_DIRS) -name *.c -or -name *.s) OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) DEPS := $(OBJS:.o=.d) #source code for shared lib SRC_SHARED = $(wildcard src_shared/*.c) #OBJ_SHARED = $(SRC:.c=.o) OBJ_SHARED = $(SRC_SHARED:%=$(BUILD_DIR)/%.o) #include/HeadhFile path info INC_DIRS := $(shell find $(SRC_DIRS) -type d) INC_DIRS += ./include INC_FLAGS := $(addprefix -I,$(INC_DIRS)) CPPFLAGS ?= $(INC_FLAGS) -MMD -MP CFLAGS ?= $(INC_FLAGS) -MMD -MP CFLAGS_SHARED ?= -fPIC -shared #DEBFLAGS ?= -O2 -g DEBFLAGS ?= -O -g -Wall # "-O" is needed to expand inlines #DEBFLAGS ?= -O -g -DSCULL_DEBUG # "-O" is needed to expand inlines .DEFAULT: compile compile : $(BUILD_DIR)/$(TARGET_EXEC) $(BUILD_DIR)/libs/$(TOP_OBJ_SHARED) echo "Here get : " $(BUILD_DIR)/$(TOP_OBJ_SHARED) $(BUILD_DIR)/$(TARGET_EXEC) #compile: $(BUILD_DIR)/$(TOP_OBJ_SHARED) $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(OBJ_SHARED) $(CC) $(OBJS) $(OBJ_SHARED) -o $@ $(LDFLAGS) ### shared lib, the name of libs is set by manual. $(BUILD_DIR)/libs/$(TOP_OBJ_SHARED): $(SRC_SHARED) $(MKDIR_P) $(dir $@) $(CC) $(SRC_SHARED) $(CFLAGS_SHARED) -o $@ # $(CC) $(SRC_SHARED) $(CFLAGS) $(CFLAGS_SHARED) -o $@ # $(CC) $(SRC_SHARED) -o $@ -fPIC -shared # $(CC) $(OBJ_SHARED) -o $@ $^ $(LDFLAGS) # $(MKDIR_P) $(dir $@) ## $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ # assembly $(BUILD_DIR)/%.s.o : %.s $(MKDIR_P) $(dir $@) $(AS) $(ASFLAGS) -c $< -o $@ # c source #$(BUILD_DIR)/%.c.o: %.c $(BUILD_DIR)/%.c.o: %.c $(MKDIR_P) $(dir $@) $(CC) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ # c++ source $(BUILD_DIR)/%.cpp.o: %.cpp $(MKDIR_P) $(dir $@) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ #.PHONY: compile #$(info "run $(BUILD_DIR)/$(TARGET_EXEC)") run: # echo "run $(BUILD_DIR)/$(TARGET_EXEC) .........." $(BUILD_DIR)/$(TARGET_EXEC) #.PHONY: run #all : clean $(BUILD_DIR)/$(TARGET_EXEC) #all : clean compile run all : clean compile #.DEFAULT: all #.PHONY: all .PHONY: clean clean: $(RM) -r $(BUILD_DIR) -include $(DEPS) MKDIR_P ?= mkdir -p <file_sep>#include <stdio.h> int function_shared_test10(int arg0) { printf("-------------------------------------------------- \n"); printf("hi, test10 \n"); printf("Here is the funciton %s \n", __func__); printf("the argo is 0x%x\n",arg0); printf("-------------------------------------------------- \n"); return (arg0 + 1); } <file_sep>#include <stdio.h> #include <string.h> #include "say_hello_08.h" #include "test08.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test08 \n"); printf("\n"); say_hello08(); char ustring1[] = "This_is_string1"; char ustring2[200]; char ustring3[200]; char *ustring4[10]; /*pointer array, the element is point to constant string*/ char *ustring5; /*char pointer*/ char (*ustring6[])[] = { &"blah", &"hmm" }; /*pointer point to string array*/// only since you brought up the syntax - char ustring_array_07[20][600]; /*pointer array, the element is point to constant string*/ //char (*ustring_array_07[20])[600]; /*pointer array, the element is point to constant string*/ printf("the contents of string1 is %s \n", ustring1); //strlcpy is not ANSI C lib yet now //strcpy(ustring2, ustring1); //strlcpy(ustring2, ustring1, sizeof(ustring1[])); //strlcpy(ustring2, ustring1, 100); strncpy(ustring2, ustring1, 100); printf("the contents of string2 is %s \n", ustring2); strcpy(ustring3, ustring1); //strncpy(ustring3, ustring1, sizeof(ustring1[])); printf("the contents of string3 is %s \n", ustring3); ustring4[0] = "This_is string4-0"; ustring4[1] = "This_is string4-1"; ustring4[2] = "This_is string4-2"; //ustring4[2] = {'T' ,'h' ,'i' ,'s' ,'_' ,'i' ,'s' ,' ' ,'s' ,'t' ,'r' ,'i' ,'n' ,'g' ,'4' ,'-' ,'2' ,'\0'}; printf("the contents of string4-0 is %s \n", ustring4[0]); printf("the contents of string4-1 is %s \n", ustring4[1]); printf("the contents of string4-2 is %s \n", ustring4[2]); ustring5 = "This_is string5"; printf("the contents of string5 is %s \n", ustring5); ustring6[0] = &"This_is string6-0"; ustring6[1] = &"This_is string6-1"; printf("the contents of string6-0 is %s \n", *ustring6[0]); printf("the contents of string6-1 is %s \n", *ustring6[1]); printf("the contents of ustring_array_test08-9 is [%s] \n", ustring_array_test08[9]); //char *ustring_array_07[]= /*pointer array, the element is point to constant string*/ sprintf(ustring_array_07[0], "Contents Start: "); //snprintf(ustring_array_07[0] ,30 ,", [0x%x] " ,uarray_test08[0]); sprintf(ustring_array_07[0], ", [0x%x] " ,uarray_test08[0]); //strlcat(ustring_array_07[0] ,ustring_array_test08[0] ,30); strncat(ustring_array_07[0] ,ustring_array_test08[0] ,30); //strcat(ustring_array_07[0], ustring_array_test08[0]); //strcpy(ustring_array_07[0], ustring_array_test08[0]); printf("the contents of ustring_array_test08-0 is [%s] \n", ustring_array_07[0]); printf("\n"); printf("Bye test08 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#include <stdio.h> int say_hello_uart() { printf("hi, test_uart \n"); return 0; } <file_sep>#include <stdio.h> int say_hello12() { printf("hi, test12 \n"); return 0; } <file_sep>#include <stdio.h> #include "say_hello_03.h" int main() { printf("hell test03 \n"); say_hello03(); return 0; } <file_sep>#include <stdio.h> //#include "say_hello_uart.h" //#include "test_uart_shared.h" #include "test_uart.h" // extern int _fd; // extern char *_cl_port; //unsigned char * _write_data; #include <unistd.h> //for usleep(usecond_t usec) int main() { #if PRINT_DEBUG_ENABLE printf("\n"); printf("===================================================\n"); printf("hello test_uart \n"); printf("\n"); #endif #if 0 say_hello_uart(); printf("Try to call function_shared_test_uart(1), get: 0x%x \n" , function_shared_test_uart(1) ); #endif #if 0 int uart_api(); #endif //todo //uart and timestamp #if 1 //uart operation here start char serial_port_name[]="/dev/ttyUSB0"; int serial_speed = 115200; #if PRINT_DEBUG_ENABLE printf("check %s, get _fd is %d\n" ,_cl_port ,_fd); #endif //init the port setup_serial_port_01(serial_port_name, serial_speed); #if PRINT_DEBUG_ENABLE printf("open %s, get _fd is %d\n" ,_cl_port ,_fd); #endif //clear the status of serial clear_custom_speed_flag(); #if 1 //for time_log check here init_time_stamp_log(); #endif //try to write hello string //write_hello_string(); //write_order_hex(); //write_out_hex_with_reorder(0x7654321 ,0xfedcba98); //TODO//worked #if 0 write_out_hex_with_reorder(0x01234567 ,0x89abcdef); #endif //TODO//worked????? #if 0 read_in_hex_with_reorder(0x01234567); #endif #if 1 unsigned int temp_data; temp_data = ir_read_register(0x00801024); #if 1 //PRINT_DEBUG_ENABLE printf("#####get temp_data is 0x%08x in %s\n" ,temp_data ,__func__); #endif or_write_register(0x00801024 ,0x65457c04); //ir 00801024 ;# read LDO_CTRL_REG, check default value 65457c04 //or 00801024 65457c04 ;# 1. LDO enable temp_data = ir_read_register(0x00801000); #if 1 //PRINT_DEBUG_ENABLE printf("#####get temp_data is 0x%08x in %s\n" ,temp_data ,__func__); #endif or_write_register(0x00801000 ,0x0c800b10); //ir 00801000 ;# read PLL_CTRL_REG, check default value 0c800b10 //or 00801000 0c800b10 ;# 2. set DDRC_PLL_DDR_DIV_SEL 0, set PLL_LOOP_PI_SEL 0 #endif //try to read the data from serial port //TODO//read_one_time_string(); //TODO #if 0 #if PRINT_DEBUG_ENABLE printf("Try to delay 1000ms delay\n"); #endif usleep(1000000); //int usleep(useconds_t usec); clock_gettime(CLOCK_MONOTONIC, &last_timeout); //for time_log check here check_time_stamp_log_data(); #endif atexit(&exit_handler); #endif //TODO #if 0 //function for file operation *p_file_name = "test_uart_file_test_func.txt"; file_init_func(p_file_name); char argv[] = "Try to write file test with func!"; file_write_func(argv); file_read_by_line_func(p_fp_global); #endif #if 0 { //file operation files #include <stdio.h> //FILE file_init_func(char *p_file_name) { //return the file handler FILE *p_fp; char *p_file_name[] = "test_uart_file_test.txt"; //FILE *fopen(char *filename, char *mode); //p_fp = fopen("test_uart_file_test.txt", "a+"); //p_fp = fopen(p_file_name, "a+"); //fclose(p_fp); //return fp; // } // //file_write_func(FILE *p_fp ,char argv[]) // { //file write case //open, write and close //p_fp = fopen("test_uart_file_test.txt", "a+"); int wr_ret = 0; //char argv[] = "Try to write file test from test_uart.c file!\n"; char argv[] = "Try to write file test from test_uart.c file!"; #if PRINT_DEBUG_ENABLE printf("the write contents is %s\n" ,argv); #endif //write(int p_fd, const void *buf, size_t count); p_fp = fopen(p_file_name, "a+"); //p_fp = fopen(p_file_name, "w+"); #if PRINT_DEBUG_ENABLE printf("Try #####fwrite() function in %s\n" ,__func__); #endif // //p_fp = fopen(p_file_name, "a+"); //size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) //fread, fwrite - binary stream input/output //wr_ret = fwrite(argv ,sizeof(argv) ,1 ,p_fp); #if PRINT_DEBUG_ENABLE printf("wr_ret is 0x%x\n" ,wr_ret); #endif #if PRINT_DEBUG_ENABLE printf("Try #####fwrite() function in %s\n" ,__func__); #endif //wr_ret = fwrite(argv ,1 ,sizeof(argv) ,p_fp); ////int fprintf(FILE *fp, char *format, e1,e2,......en); //#if PRINT_DEBUG_ENABLE // printf("wr_ret is 0x%x\n" ,wr_ret); //#endif #if PRINT_DEBUG_ENABLE printf("Try #####fprintf() function in %s\n" ,__func__); #endif fprintf(p_fp ,"fprintf %s\n" ,argv); fclose(p_fp); //return 0; // } // //file_read_by_line_func(FILE *p_fp ) // { //file read and write case //open, write and close char *line_buf = NULL; int line_count = 0; //char *p_file_name = "test_uart_file_test.txt"; //p_fp = fopen(p_file_name, "a+"); #if PRINT_DEBUG_ENABLE //printf("Try to open file %s\n\r" ,p_file_name); printf("Try to open file %s\n" ,p_file_name); #endif #if 1 p_fp = fopen(p_file_name, "r+"); #if PRINT_DEBUG_ENABLE printf("Try #####getline() function in %s\n" ,__func__); #endif size_t line_buf_size = 0; ssize_t line_size; /* Get the first line of the file. */ line_size = getline(&line_buf, &line_buf_size, p_fp); line_count = 0; /* Loop through until we are done with the file. */ while (line_size >= 0) { /* Increment our line count */ line_count++; #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("line[%06d]: chars=%06zd, buf size=%06zu, contents: %s\n" ,line_count ,line_size ,line_buf_size ,line_buf); #endif /* Get the next line */ line_size = getline(&line_buf ,&line_buf_size ,p_fp); } #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("The total lines is %d\n" ,line_count); #endif fclose(p_fp); #endif //not worked #if 0 p_fp = fopen(p_file_name, "r+"); #if PRINT_DEBUG_ENABLE printf("Try #####fscanf() function in %s\n" ,__func__); #endif char line_data[128] = {0}; //while (fscanf(p_fp, "%[^\n]", line_data) != EOF) while (fscanf(p_fp, "%[\n]" ,line_data) != EOF) { printf("> %s\n", line_data); } fclose(p_fp); #endif //worked for txt format with end of line char #if 0 p_fp = fopen(p_file_name, "r+"); #if PRINT_DEBUG_ENABLE printf("Try #####fgets() function in %s\n" ,__func__); #endif //char *path; //char line[MAX_LINE_LENGTH] = {0}; char line[128] = {0}; //char line[128]; //unsigned int line_count = 0; line_count = 0; /* Get each line until there are none left */ //while (fgets(line, MAX_LINE_LENGTH, file)) while (fgets(line, 128, p_fp)) { /* Print each line */ printf("line[%06d]: %s", ++line_count, line); /* Add a trailing newline to lines that don't already have one */ if (line[strlen(line) - 1] != '\n') { printf("\n"); } } #if PRINT_DEBUG_ENABLE /* Show the line details */ printf("The total lines is %d\n" ,line_count); #endif fclose(p_fp); #endif /* Free the allocated line buffer */ free(line_buf); line_buf = NULL; /* Close the file now that we are done with it */ //fclose(p_fp); //int fscanf(FILE *fp, char *format, e1,e2,......en); //int fread(char *buf, unsigned size, unsigned n, FILE *fp); //fclose(p_fp); //return 0; } } #endif #if PRINT_DEBUG_ENABLE printf("\n"); printf("Bye test_uart \n"); printf("===================================================\n"); printf("\n"); #endif return 0; } <file_sep>#!/bin/bash # scons -c #scons #scons --tree=all scons --tree=status ./test13 #scons -c <file_sep># # #meaning of specific strings #*# $@ all of FileNameWithExtension produced # $* all of FileNameWithoutExtension produced # $< the FileName of first dependance item #*# $^ the dependance items with space islated and remove the repeated item # $+ the dependance items with space islated, but do not remove the repeated item # $? the dependance items with space islated, but just have the new item # # define a variable, Var=xx , and the methods of using variable is $(Var) # #search path # VPATH = src include # vpath %.c src # vpath %.h include # #match standard # %.o: %.c # # %.o: %.c # gcc -g -o $@ -c $< # #update_content#CC=gcc #update_content#CFLAGS = -I ./include #update_content#DEPS = say_hello_06.h #update_content# #update_content#TARGET=test06 #update_content# #update_content##all: test06 #update_content#all: $(TARGET) #update_content# #update_content##test06 : ./src/say_hello_06.c ./src/test06.c #update_content#$(TARGET): ./src/say_hello_06.c ./src/test06.c #update_content# $(CC) -g -o $@ $^ $(CFLAGS) #update_content## $(CC) -o test06 ./src/say_hello_06.c ./src/test06.c $(CFLAGS) #update_content## gcc -o test06 ./src/say_hello_06.c ./src/test06.c -I ./include #update_content# #update_content#clean: #update_content## rm test06 #update_content# rm $(TARGET) #CC=gcc CC=clang TARGET_EXEC ?= test06 BUILD_DIR ?= ./build_gcc SRC_DIRS ?= ./src #all: $(TARGET_EXEC) #source code info #SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c -or -name *.s) SRCS := $(shell find $(SRC_DIRS) -name *.c -or -name *.s) OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) DEPS := $(OBJS:.o=.d) #include/HeadhFile path info INC_DIRS := $(shell find $(SRC_DIRS) -type d) INC_DIRS += ./include INC_FLAGS := $(addprefix -I,$(INC_DIRS)) CPPFLAGS ?= $(INC_FLAGS) -MMD -MP $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(CC) $(OBJS) -o $@ $(LDFLAGS) # assembly $(BUILD_DIR)/%.s.o: %.s $(MKDIR_P) $(dir $@) $(AS) $(ASFLAGS) -c $< -o $@ # c source $(BUILD_DIR)/%.c.o: %.c $(MKDIR_P) $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ # c++ source $(BUILD_DIR)/%.cpp.o: %.cpp $(MKDIR_P) $(dir $@) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ run: $(BUILD_DIR)/$(TARGET_EXEC) .PHONY: clean clean: $(RM) -r $(BUILD_DIR) -include $(DEPS) MKDIR_P ?= mkdir -p <file_sep>#include <stdio.h> #include "say_hello_10.h" #include "test10_shared.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test10 \n"); printf("\n"); say_hello10(); printf("Try to call function_shared_test10(1), get: 0x%x \n" , function_shared_test10(1) ); printf("\n"); printf("Bye test10 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#!/bin/bash # scons -c #scons #scons --tree=all scons --tree=status ./test_uart #scons -c <file_sep>#include <stdio.h> #include "say_hello_04.h" int main() { printf("hello test05 \n"); say_hello04(); return 0; } <file_sep>#!/bin/bash # scons -c #scons #scons --tree=all scons --tree=status #./test14 #./Test14 arg1 arg2 arg3 arg4 arg5 arg6 #./test14 arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 ./test14 arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 --File /home/data/outputdata.txt #scons -c <file_sep>#include <stdio.h> int say_hello11() { printf("hi, test11 \n"); return 0; } <file_sep>#ifndef __TEST08_H__ #define __TEST08_H__ char *ustring_array_test08[]= /*pointer array, the element is point to constant string*/ { "00 This is contents of element of string array test08" , "01 This is contents of element of string array test08" , "02 This is contents of element of string array test08" , "03 This is contents of element of string array test08" , "04 This is contents of element of string array test08" , "05 This is contents of element of string array test08" , "06 This is contents of element of string array test08" , "07 This is contents of element of string array test08" , "08 This is contents of element of string array test08" , "09 This is contents of element of string array test08" , "10 This is contents of element of string array test08" , "11 This is contents of element of string array test08" }; int uarray_test08[]= { 0x0 , 0x01 , 0x02 , 0x03 , 0x04 , 0x05 , 0x06 , 0x07 , 0x08 , 0x09 , 0x10 , 0x11 }; #endif <file_sep>#ifndef __SAY_HELLO_03_H__ #define __SAY_HELLO_03_H__ int say_hello03(); #endif<file_sep>#!/bin/bash \rm -rf ./build_* scons -c \rm -rf .sconsign.dblite* \rm -rf autoscan.log* \rm -rf fshan_cbuild_log.txt \rm -rf *.i \rm -rf *.s \rm -rf *.o \rm -rf *.bc <file_sep>#Library('',[]) #Library('Test14SharedLib', ['../src_shared/test14_shared.c']) #Library('Test14SharedLib', ['../src_shared/test14_shared.c'] ,CPPPATH=['../include']) #Program('',[]) Import("env") Import("opt") Import("dbg") # #env.Program('test14' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test14SharedLib'] ,LIBPATH=['../build_sc_shared']) #obj = env.Object([Glob('./src/*.c[cp]*')]) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header']) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header' ,'../libs/shared/header' ,'../libs/say_hello/header' ,'../libs/practice/header']) obj = env.Object([Glob('./src/*.c')] ,CCFLAGS='' ,CPPPATH=[ './header' , '../libs/shared/header' , '../libs/arg_read/header' , '../libs/say_hello/header']) # ,'../libs/practice/header' Return('obj') #opt.Program('test14-opt' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test14SharedLib'] ,LIBPATH=['../src_shared']) #dbg.Program('test14-dbg' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['Test14SharedLib'] ,LIBPATH=['../src_shared']) <file_sep>#ifndef __TEST_SHARED_H__ #define __TEST_SHARED_H__ int function_shared_test(int arg0); #endif <file_sep>#ifndef __TEST11_SHARED_H__ #define __TEST11_SHARED_H__ int function_shared_test11(int arg0); #endif <file_sep>#ifndef __SAY_HELLO_08_H__ #define __SAY_HELLO_08_H__ int say_hello08(); #endif <file_sep>#Library('',[]) #Library('Test12SharedLib', ['../src_shared/test12_shared.c']) #Library('Test12SharedLib', ['test12_shared.c'] ,CPPPATH=['../include']) #StaticLibrary('Test12SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Library('Test12SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Import('env') Import('*') env.Library('Test12SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Program('',[]) #Program('test12' ,['../src/test12.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_12.c'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['../src/test12.c' ,'../src/say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['../src/test12.c' ,'../src/say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) <file_sep>/* * main.c * * Created on: Oct 26, 2016 * Author: qshan */ #include <stdio.h> #include <stdlib.h> #include <practice.h> int main() { printf("\n##this is start of %s in %s##\n", __func__, __FILE__); int i=0; #if 0 //test for behavior of sizeof for pointer unsigned int array[3][2] = {{1,2},{3,4},(5,6)}; unsigned int *ptr1; unsigned int *ptr2; unsigned int *ptr3; ptr1 = array; ptr2 = array[0]; ptr3 = &array[0][1]; //printf("array is %x\n", array); printf("sizeof(array) is %d \n", (sizeof(array))); printf("sizeof(typeof(array)) is %d \n", (sizeof(typeof(array)))); printf("sizeof(array[0]) is %d \n", (sizeof(array[0]))); printf("sizeof(typeof(array[0])) is %d \n", (sizeof(typeof(array[0])))); printf("sizeof(array[0][0]) is %d \n", (sizeof(array[0][0]))); printf("sizeof(ptr1) is %d \n", (sizeof(ptr1))); printf("sizeof(typeof(ptr1)) is %d \n", (sizeof(typeof(ptr1)))); printf("sizeof(ptr2) is %d \n", (sizeof(ptr2))); printf("sizeof(ptr3) is %d \n", (sizeof(ptr3))); printf("sizeof(*ptr1) is %d \n", (sizeof(*ptr1))); printf("sizeof(*ptr2) is %d \n", (sizeof(*ptr2))); printf("sizeof(*ptr3) is %d \n", (sizeof(*ptr3))); #endif #if 0 for (i=0;i<10;i++) printf("Hell C %d time \n", (i+1)); #endif #if 0 //just example for my son /**/ // i=0; if(i==0) { //code block printf("i=0 is right\n"); }else { //code block printf("i != 0\n"); printf("i is really not equal 0\n"); } //add in qcavi pc printf("the code is end here\n"); #endif #if 0 //for the enmu test enum TRAFFIC_TYPE {type_one, type_two, type_three, type_four}; enum TRAFFIC_TYPE sellection; sellection = type_three; switch (sellection) { case type_one : printf("current is type_one \n"); break; case type_two : printf("current is type_two \n"); break; case type_three : printf("current is type_three \n"); break; case type_four : printf("current is type_four \n"); break; default : //code here; printf("current is default branch \n"); break; } #endif #if 0 //test for behavior of sizeof for array int Array[]={10,9,8,2,6,5,4,3,7,1}; //printf("sizeof(Array) = %d\n", (sizeof(Array))); //printf("sizeof(Array[0]) = %d\n", (sizeof(Array[0]))); //printf("sizeof(Array)/sizeof(Array[0]) = %d\n", (sizeof(Array)/sizeof(Array[0]))); printf("sizeof(Array)/sizeof(Array[0]) = %d\n", (NUMBEROFARRAYD1(Array))); print_int_array(Array, (sizeof(Array)/sizeof(Array[0]))); sort_int(Array, sizeof(Array)/sizeof(Array[0])); print_int_array(Array, (sizeof(Array)/sizeof(Array[0]))); #endif #if 0 //dlist //declare a struct qs_DLIST_NODE qs_dlist; //declare a pointer of struct qs_DLIST_PTR qs_dlistptr; //qs_DLIST_NODE *qs_dlistptr; #if 0 printf("\n [integer]: sizeof(int) is %d", sizeof(int)); printf("\n [struct]: sizeof(qs_dlist) is %d", sizeof(qs_dlist)); printf("\n [pointer of struct]: sizeof(qs_dlistptr) is %d", sizeof(qs_dlistptr)); //printf("\n Here is code line number %d in %s \n", __LINE__, __FILE__); #endif qs_dlistptr = qs_dlist_create(); qs_dlist_insert_R(qs_dlistptr, 1, 2); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 2, 3); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 7, 4); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 2, 5); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 2, 6); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 5, 9); qs_dlist_print(qs_dlistptr); qs_dlist_insert_R(qs_dlistptr, 4, 7); qs_dlist_print(qs_dlistptr); qs_dlist_delete(qs_dlistptr, 5); qs_dlist_print(qs_dlistptr); qs_dlist_delete(qs_dlistptr, 7); qs_dlist_print(qs_dlistptr); qs_dlist_delete(qs_dlistptr, 2); qs_dlist_print(qs_dlistptr); #endif #if 0 //queue##### FIFO qs_QUEUE Q; qs_InitQueue(&Q, 5); qs_PrintQueue(&Q); qs_EnQueue(&Q, 1); qs_PrintQueue(&Q); qs_EnQueue(&Q, 2); qs_PrintQueue(&Q); qs_EnQueue(&Q, 3); qs_PrintQueue(&Q); qs_EnQueue(&Q, 4); qs_PrintQueue(&Q); qs_EnQueue(&Q, 5); qs_PrintQueue(&Q); qs_EnQueue(&Q, 6); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); qs_DeQueue(&Q); qs_PrintQueue(&Q); //qs_InitQueue //qs_EnQueue //qs_DeQueue //qs_IsQueueEmpty //qs_IsQueueFull #endif #if 0 //linked stack##### qs_LSTACK_NODE temp_lstack; qs_LSTACK_NODE_PTR temp_lstack_ptr = &temp_lstack; qs_lStackInit(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPush(temp_lstack_ptr, 1); qs_lStackPrint(temp_lstack_ptr); qs_lStackPush(temp_lstack_ptr, 2); qs_lStackPrint(temp_lstack_ptr); qs_lStackPush(temp_lstack_ptr, 3); qs_lStackPrint(temp_lstack_ptr); qs_lStackPush(temp_lstack_ptr, 4); qs_lStackPrint(temp_lstack_ptr); qs_lStackPush(temp_lstack_ptr, 5); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); qs_lStackPop(temp_lstack_ptr); qs_lStackPrint(temp_lstack_ptr); #endif #if 1 //here is a global power state definition unsigned int SocSystemPowerState = POWER_OFF; unsigned int LoadCPUImageReady = 0; //just for Core1~3,set by cmm unsigned int LoadCPUImageRequest = 0; //set by Core0 in C unsigned int LoadWifiReady = 0; //set by cmm, to load wifi image, how get the wifi feedback? unsigned int LoadWifiRequest = 0; //set by Core0 in C unsigned int SystemError = 0; unsigned int SystemNum = 0; unsigned int PowerOnEnable = POWER_MODE_TRAN_ENABLE; unsigned int LowPowerEnterEnable = POWER_MODE_TRAN_ENABLE; unsigned int LowPowerExitEnable = POWER_MODE_TRAN_ENABLE; i = 5; while(i>0) { i--; switch(SocSystemPowerState) { case POWER_OFF: printf("here is Power Off state \n"); if (PowerOnEnable == POWER_MODE_TRAN_ENABLE) { //power mode transition from power off to power on function// initial function //normal basic check for next power state(power on) //SystemError = SOCPowerOnBasicCheck(); //if succeed, set the power state as Power on state SocSystemPowerState = POWER_ON; }else { printf("do not power on initial\n"); } break; case POWER_ON: printf("here is PowerOn state\n"); if(LowPowerEnterEnable == POWER_MODE_TRAN_ENABLE) { //power mode transition from power on to low power function //SystemError = SOCLowPowerEnter(); //normal basic check for next power state(low power) //SystemError = SOCLowPowerBasicCheck(); //if succeed, set the power state as low power state SocSystemPowerState = LOW_POWER; }else { printf("do those function test in power on state\n"); } break; case LOW_POWER: printf("here is LowPower state\n"); if(LowPowerExitEnable == POWER_MODE_TRAN_ENABLE) { //power mode transition from low power to power on function //SystemError = SOCLowPowerExit(); //normal basic check for next power state(low power) //SystemError = SOCPowerOnBasicCheck(); //if succeed, set the power state as PowerOn state SocSystemPowerState = POWER_ON; }else { printf("do those function test in low power state\n"); } break; default : printf("abnormal branch in system power state case\n"); break; } } #endif #if 0 //to check a number list in lmbench //typedef long unsigned int LUI_NUB LUI_NUB LOWER = 512; LUI_NUB len = 1024*1024; LUI_NUB range = 0; LUI_NUB step(LUI_NUB k); printf("len is : %d (1024*1024)\n", len); for (range = LOWER; range <= len; range = step(range)) { // loads(len, range, stride, parallel, // warmup, repetitions); printf("range is : %dk : %d\n", (range/1024),range); } #endif //================================================================// i++; printf("\n##this is end of %s in %s##\n", __func__, __FILE__); printf("\n^-^ ##this is end of ctest_qshan## ^-^\n"); return 0; } //to check a number list in lmbench LUI_NUB step(LUI_NUB k) { if (k < 1024) { k = k * 2; } else if (k < 4*1024) { k += 1024; } else { LUI_NUB s; for (s = 4 * 1024; s <= k; s *= 2) ; k += s / 4; } return (k); } <file_sep>#!/bin/bash \rm -rf ./build_* scons -c <file_sep>#ifndef __TEST14_SHARED_H__ #define __TEST14_SHARED_H__ int function_shared_test14(int arg0); #endif <file_sep>#ifndef __TEST10_SHARED_H__ #define __TEST10_SHARED_H__ int function_shared_test10(int arg0); #endif <file_sep>#!/bin/bash # run like this #cmake -G "Unix Makefiles" .. #cmake .. ##set in CMakeList.tx or set here, one times is enough cmake -DCMAKE_BUILD_TYPE=Debug .. #cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .. #cmake -DCMAKE_BUILD_TYPE=Release .. make clean make ./Test08_Hello <file_sep>#include <stdio.h> #include "test13.h" //#include "say_hello_13.h" //#include "test13_shared.h" int main() { printf("\n"); printf("===================================================\n"); printf("hello test13 \n"); printf("\n"); say_hello13(); printf("Try to call function_shared_test13(1), get: 0x%x \n" , function_shared_test13(1) ); printf("\n"); printf("Bye test13 \n"); printf("===================================================\n"); printf("\n"); return 0; } <file_sep>#!/bin/bash # run like this export Test13BuildPath="./build_cmake" export Test13SourcePath="." #cmake3.13#cmake -B${Test13BuildPath} -S${Test13SourcePath} cmake -B${Test13BuildPath} -H${Test13SourcePath} cd ${Test13BuildPath} make clean make ./Test13 cd - <file_sep>#ifndef __FILE_LOG_H__ #define __FILE_LOG_H__ //file_log.h #include <stdio.h> #ifndef PRINT_DEBUG_ENABLE #define PRINT_DEBUG_ENABLE 1 #endif #define MAX_NUMBER_PER_LINE 200 #define MAX_NUMBER_FILENAME 200 extern FILE *p_fp_global; extern char *p_file_name[]; //FILE file_init_func(char *p_file_name[]); //int file_init_func(char *p_file_name[1024]); int file_init_func(char *p_file_name[]); int file_write_func(char argv[]); int file_read_by_line_func(FILE *p_fp ); #endif <file_sep># run like this cd ./build #cmake -G "Unix Makefiles" .. cmake .. make echo "please makesure the lib is in ../lib path" ./Test05_Hello <file_sep>#Import('env') Import('*') #env.Library('TestSharedLib' ,Glob('*.c[cp]*') ,CPPPATH=['../header']) #env.StaticLibrary('TestStaticSharedLib' ,Glob('./src/*.c[cp]*') ,CPPPATH=['./header']) #env.SharedLibrary('TestSharedSharedLib' ,Glob('./src/*.c[cp]*') ,CPPPATH=['./header']) #env.SharedLibrary('TestSharedSharedLib' ,Glob('./src/*.c[cp]*') ,CPPPATH=['./header']) env.SharedLibrary('TestSharedSharedLib' ,Glob('./src/*.c') ,CPPPATH= [ './header' #TODO# add item one by one by manual #, './header' ] ) #obj = env.Object([Glob('./src/*.c[cp]*')]) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header']) obj = env.Object([Glob('./src/*.c')] ,CCFLAGS='' ,CPPPATH=['./header']) Return('obj') <file_sep>#Library('',[]) #Library('TestUartSharedLib', ['../src_shared/test_uart_shared.c']) #Library('TestUartSharedLib', ['../src_shared/test_uart_shared.c'] ,CPPPATH=['../include']) #Program('',[]) Import("env") Import("opt") Import("dbg") # #env.Program('test_uart' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['TestUartSharedLib'] ,LIBPATH=['../build_sc_shared']) #obj = env.Object([Glob('./src/*.c[cp]*')]) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header']) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header' ,'../libs/shared/header' ,'../libs/say_hello/header' ,'../libs/practice/header']) obj = env.Object([Glob('./src/*.c')] ,CCFLAGS='' ,CPPPATH=[ './header' , '../libs_shared/shared/header' , '../libs/uart/header' , '../libs/file_log/header' , '../libs/time_stamp_log/header' , '../libs/say_hello/header']) # ,'../libs/practice/header' Return('obj') #opt.Program('test_uart-opt' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['TestUartSharedLib'] ,LIBPATH=['../src_shared']) #dbg.Program('test_uart-dbg' ,Glob('*.c') ,CPPPATH=['../include'] ,LIBS=['TestUartSharedLib'] ,LIBPATH=['../src_shared']) <file_sep>#ifndef __SAY_HELLO_14_H__ #define __SAY_HELLO_14_H__ int say_hello14(); #endif <file_sep># # #meaning of specific strings #*# $@ all of FileNameWithExtension produced # $* all of FileNameWithoutExtension produced # $< the FileName of first dependance item #*# $^ the dependance items with space islated and remove the repeated item # $+ the dependance items with space islated, but do not remove the repeated item # $? the dependance items with space islated, but just have the new item # % # #automatic variables Descriptions #*# $@ The file name of the target # $< The name of the first prerequisite #*# $^ The names of all the prerequisites # $+ Prerequisites listed more than once are duplicated in the order # # define a variable, Var=xx , and the methods of using variable is $(Var) # #search path # VPATH = src include # vpath %.c src # vpath %.h include # #match standard # %.o: %.c # # %.o: %.c # gcc -g -o $@ -c $< # # #.PHONY: all #info#this items is for no dependance item #------------------------------ #CC=gcc #CXX=g++ CC=clang CXX=clang++ #------------------------------ #set target name TARGET_EXEC ?= test13 #------------------------------ #set project/code root path PRO_ROOT_PATH = . #set the build path, the temp file path export BUILD_DIR ?= $(PRO_ROOT_PATH)/build_make $(info "BUILD_DIR is $(BUILD_DIR)") #export $$BUILD_DIR #------------------------------ #test code SRC_DIRS ?= $(PRO_ROOT_PATH)/test/src #libs code #INC_DIRS := $(shell find $(SRC_DIRS) -type d) #TODO#Add the src by manual SRC_DIRS += $(PRO_ROOT_PATH)/libs/say_hello/src #SRC_DIRS += $(PRO_ROOT_PATH)/libs/practice/src #Add the src by searching #TODO#conflicted with shared#SRC_DIRS += $(shell find ./libs -type d -iname "*src") #shared libs code #get the shared path here SRC_SHARED_DIRS ?= $(PRO_ROOT_PATH)/libs/shared/src #log define BUILD_LOG_FILE ?= $(BUILD_DIR)/$(TARGET_EXEC).log #share lib name defined TOP_OBJ_SHARED ?= Test13SharedLib.o #$(BUILD_LOG_FILE): # $(MKDIR_P) $(BUILD_DIR) # touch $(BUILD_DIR)/$(TARGET_EXEC).log #all: $(TARGET_EXEC) #source code for shared lib SRC_SHARED = $(wildcard \ $(SRC_SHARED_DIRS)/*.c \ $(SRC_SHARED_DIRS)/*.cpp) $(info "SRC_SHARED is $(SRC_SHARED)") OBJ_SHARED = $(SRC_SHARED:%=$(BUILD_DIR)/%.o) #ToCheck #include/HeadhFile path for shared lib generating info INC_DIRS_SHARED := $(PRO_ROOT_PATH)/libs/shared/header $(info "INC_DIRS_SHARED is $(INC_DIRS_SHARED)") INC_FLAGS_SHARED := $(addprefix -I,$(INC_DIRS_SHARED)) $(info "INC_FLAGS_SHARED is $(INC_FLAGS_SHARED)") CFLAGS_SHARED ?= $(INC_FLAGS_SHARED) -fPIC -shared CPPFLAGS_SHARED ?= $(INC_FLAGS_SHARED) -fPIC -shared #source code info SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c -or -name *.s) OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) DEPS := $(OBJS:.o=.d) #include/HeadhFile path for source code info INC_DIRS := $(shell find $(SRC_DIRS) -type d) $(info "INC_DIRS is $(INC_DIRS)") INC_DIRS += $(PRO_ROOT_PATH)/test/header \ $(PRO_ROOT_PATH)/libs/say_hello/header \ # $(PRO_ROOT_PATH)/libs/practice/header INC_DIRS += $(INC_DIRS_SHARED) INC_FLAGS := $(addprefix -I,$(INC_DIRS)) CFLAGS ?= $(INC_FLAGS) -MMD -MP CPPFLAGS ?= $(INC_FLAGS) -MMD -MP #------------------------------ #compile option here # '-g' is for dgb support DEBFLAGS += -g # '-O0' is optimize for faster compilation and build time #DEBFLAGS ?= -O0 # '-O3' is optimize for performance #DEBFLAGS ?= -O3 # '-Omin' is optimize for code size DEBFLAGS ?= -Omin # '-Wall' is to enable the all warning DEBFLAGS += -Wall # '-Werror' is to make all warnings into errors DEBFLAGS += -Werror # '-Wfatal-errors' is to make compile abort when the hit the errors firstly DEBFLAGS += -Wfatal-errors #DEBFLAGS ?= -O -g -DSCULL_DEBUG # "-O" is needed to expand inlines #TODO#worked DEBFLAGS += -DPRINT_DEBUG_ENABLE=1 #DEBFLAGS += -DPRINT_DEBUG_ENABLE=0 #------------------------------ #.DEFAULT: compile .DEFAULT: all compile : $(BUILD_DIR)/$(TARGET_EXEC) $(BUILD_DIR)/libs/$(TOP_OBJ_SHARED) $(info "Here get : " $(BUILD_DIR)/$(TOP_OBJ_SHARED)) #run# $(BUILD_DIR)/$(TARGET_EXEC) #compile: $(BUILD_DIR)/$(TOP_OBJ_SHARED) $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(OBJ_SHARED) $(CC) $(OBJS) $(OBJ_SHARED) $(DEBFLAGS) -o $@ $(LDFLAGS) # $(CXX) $(OBJS) $(OBJ_SHARED) -o $@ $(LDFLAGS) ### shared lib, the name of libs is set by manual. $(BUILD_DIR)/libs/$(TOP_OBJ_SHARED): $(SRC_SHARED) $(MKDIR_P) $(dir $@) $(CC) $(SRC_SHARED) $(CFLAGS_SHARED) $(DEBFLAGS) -o $@ # $(CC) $(SRC_SHARED) $(CFLAGS) $(CFLAGS_SHARED) -o $@ ## $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ # assembly $(BUILD_DIR)/%.s.o : %.s $(MKDIR_P) $(dir $@) $(AS) $(ASFLAGS) -c $< -o $@ # c source #$(BUILD_DIR)/%.c.o: %.c $(BUILD_DIR)/%.c.o: %.c $(MKDIR_P) $(dir $@) $(CC) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ # c++ source $(BUILD_DIR)/%.cpp.o: %.cpp $(MKDIR_P) $(dir $@) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DEBFLAGS) -c $< -o $@ #.PHONY: compile #$(info "run $(BUILD_DIR)/$(TARGET_EXEC)") run: $(info "####################") $(info "run $(BUILD_DIR)/$(TARGET_EXEC) ..........") $(BUILD_DIR)/$(TARGET_EXEC) #.PHONY: run #all : clean $(BUILD_DIR)/$(TARGET_EXEC) #all : clean compile run all : clean compile run #.DEFAULT: all #.PHONY: all .PHONY: clean clean: $(RM) -r $(BUILD_DIR) -include $(DEPS) MKDIR_P ?= mkdir -p <file_sep>#good doc #https://scons.org/doc/production/HTML/scons-user.html#app-functions #Library('',[]) #Library('Test12SharedLib', ['../src_shared/test12_shared.c']) #Library('Test12SharedLib', ['../src_shared/test12_shared.c'] ,CPPPATH=['../include']) #Program('',[]) #Program('',[]) #Program('test12' ,['../src/test12.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_12.c'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['../src/test12.c' ,'../src/say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #Program('test12' ,['../src/test12.c' ,'../src/say_hello_12.c'] ,CPPPATH=['../include'] ,LIBS=['Test12SharedLib'] ,LIBPATH=['.']) #SConstruct #env = Environment(CC='gcc' ,CCFLAGS=' -O2 -Wall -g' ,CPPDEFINES=['MyDefine01']) # env = Environment(CC='gcc') env.Replace(CC='clang') #env.Append(CCFLAGS=' -Wall -g') env.Append(CCFLAGS=' -O2 -Wall -g') # env.Prepend(CPPDEFINES=['MyFirstDefine00']) env.Append(CPPDEFINES=['MyDefine02']) env.Append(MyVariableAdded01=['MyVariableAdded01']) print("MyVariableAdded01 = %s" % env['MyVariableAdded01']) # opt = env.Clone(CCFLAGS=[' -O2']) dbg = env.Clone(CCFLAGS=[' -Wall -g']) # #env.Program('test12' ,['foo.c']) # #o = opt.Object('test12-o' ,['foo.c']) #opt.Program(o) ## #d = dbg.Object('test12-d' ,['foo.c']) #dbg.Program(d) Export ('env') #Export ("opt", "dbg") #Export ('opt dbg') Export ('opt', 'dbg') #Export ('dbg') #check the env setting here print("[env.CC] is %s" % env['CC']) print("[env.CXX] is %s" % env['CXX']) print("[env.CCFLAGS] is %s" % env['CCFLAGS']) BuildOutputFilePath="build_sco" Export ('BuildOutputFilePath') print("BuildOutputFilePath = %s" % BuildOutputFilePath) SConscript(['src_shared/SConscript'] # , variant_dir=BuildOutputFilePath + "/build_sc_shared" , variant_dir=BuildOutputFilePath + "/src_shared" # , variant_dir=BuildOutputFilePath , duplicate=False ) SConscript(['src/SConscript'] # , variant_dir=BuildOutputFilePath + "/build_sc" , variant_dir=BuildOutputFilePath + "/src" # , variant_dir=BuildOutputFilePath , duplicate=False ) #SConscript(['src_shared/SConscript'] ## , variant_dir='build_sc_shared' # ) #SConscript(['src/SConscript'] ## , variant_dir='build_sc' # ) <file_sep>#ifndef __TEST_UART_SHARED_H__ #define __TEST_UART_SHARED_H__ int function_shared_test_uart(int arg0); #endif <file_sep>#Import('env') Import('*') #obj = env.Object([Glob('./src/*.c[cp]*')]) #obj = env.Object([Glob('./src/*.c[cp]*')] ,CCFLAGS='' ,CPPPATH=['./header']) obj = env.Object([Glob('./src/*.c')] ,CCFLAGS='' ,CPPPATH=['./header']) Return('obj') <file_sep>#include <stdio.h> int say_hello06() { printf("hi, test06 \n"); return 0; } <file_sep>#!/usr/bash #gcc -g read_arg.c - -o read_arg #$gcc -save-temps -g3 read_arg.c - -o read_arg #gcc read_arg.c -Wl, -e main_try -o read_arg #gcc -g read_arg.c -Wl, -e main_try -o read_arg #gcc -g read_arg.c --entry=main_try -o read_arg #./read_arg arg1 arg2 arg3 arg4 arg5 arg6 --port /dev/usb0 --File /home/data/outputdata.txt \rm -rf *.i *.s *.o read_arg <file_sep>#ifndef __SAY_HELLO_13_H__ #define __SAY_HELLO_13_H__ int say_hello13(); #endif <file_sep>#ifndef __TEST_MAIN_H__ #define __TEST_MAIN_H__ #include "test_shared.h" #include "say_hello.h" #endif <file_sep># ctest_qshan the folder for the C language study and practice <file_sep>#!/bin/bash # run like this export Test13BuildPath="./build_cmake2" if [ ! -d ${Test13BuildPath} ]; then mkdir -p ${Test13BuildPath} fi if [ -d ${Test13BuildPath} ]; then cd ${Test13BuildPath} #cmake -G "Unix Makefiles" .. cmake .. make clean make # ./Test13_Hello ./Test13 cd - # mkdir build_cmake fi <file_sep>#ifndef __SAY_HELLO_12_H__ #define __SAY_HELLO_12_H__ int say_hello12(); #endif <file_sep>#ifndef __SAY_HELLO_UART_H__ #define __SAY_HELLO_UART_H__ int say_hello_uart(); #endif <file_sep># run like this cd ./build #cmake -G "Unix Makefiles" .. cmake .. make ./Test04_Hello <file_sep>#ifndef __TIME_STAMP_LOG_H__ #define __TIME_STAMP_LOG_H__ //time_stamp_log.h #ifndef PRINT_DEBUG_ENABLE #define PRINT_DEBUG_ENABLE 1 #endif #include <time.h> /* time - run programs and summarize system resource usage */ //#include <time.h> /* time - run programs and summarize system resource usage */ //struct timespec start_time[], last_stat[], last_timeout[], last_read[], last_write[]; extern struct timespec current; extern struct timespec start_time, last_stat, last_timeout, last_read, last_write; int init_time_stamp_log(); int diff_ms(const struct timespec *t1, const struct timespec *t2); int check_time_stamp_log_data(); #endif <file_sep>#ifndef __SAY_HELLO_10_H__ #define __SAY_HELLO_10_H__ int say_hello10(); #endif <file_sep># # 指定 cmake 最低编译版本 CMAKE_MINIMUM_REQUIRED(VERSION 3.5) #Project Name PROJECT (Test07_Hello) # include path #INCLUDE_DIRECTORIES(./include) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include) # add file list, SET(SRC_LIST tested01.c testates02.c) #SET(SRC_LIST ./src/test03.c) #search source file ######FILE(GLOB SRC_LIST "${PROJECT_SOURCE_DIR}/src/*.c") ######check the contents got after searching ######MESSAGE(STATUS "Get SRC_LIST is " ${SRC_LIST}) AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src src6) #check the contents got after searching MESSAGE(STATUS "Get src3 is " ${src6}) #print check the variable content in env # 输出打印构建目录 MESSAGE(STATUS "This is HELLO_BINARY_DIR " ${HELLO_BINARY_DIR}) # 输出打印资源目录 MESSAGE(STATUS "This is HELLO_SOURCE_DIR " ${HELLO_SOURCE_DIR}) # 输出打印资源目录,与HELLO_SOURCE_DIR 一样 MESSAGE(STATUS "This is PROJECT_SOURCE_DIR " ${PROJECT_SOURCE_DIR}) # 输出打印 CMake 资源目录,与 PROJECT_SOURCE_DIR 一样 MESSAGE(STATUS "This is CMAKE_SOURCE_DIR " ${CMAKE_SOURCE_DIR}) MESSAGE(STATUS "This is PROJECT " ${PROJECT}) # 生成可执行文件 hello ,${SRC_LIST}是引用变量,也就是源文件 hello.c ######ADD_EXECUTABLE(Test07_Hello ${SRC_LIST}) ADD_EXECUTABLE(Test07_Hello ${src6}) <file_sep>#include <stdio.h> int say_hello10() { printf("hi, test10 \n"); return 0; } <file_sep>###### # 指定 cmake 最低编译版本 CMAKE_MINIMUM_REQUIRED(VERSION 3.5) ##### #####PROJECT (MATH) #Project Name PROJECT (Test05_Hello) ###### 指定头文件目录 #####INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include) # include path INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include) #添加共享库搜索路径 LINK_DIRECTORIES(${PROJECT_SOURCE_DIR}/lib) #生成可执行文件 ADD_EXECUTABLE(Test05_Hello ./src/test05.c) #为hello添加共享库链接 TARGET_LINK_LIBRARIES(Test05_Hello SayHello04) #just for static lib #TARGET_LINK_LIBRARIES(Test05_Hello SayHello04.a) <file_sep># run like this #cmake -G "Unix Makefiles" .. cmake .. make clean make ./Test06_Hello <file_sep>#!/bin/bash # run like this export TestUartBuildPath="./build_cmake2" if [ ! -d ${TestUartBuildPath} ]; then mkdir -p ${TestUartBuildPath} fi if [ -d ${TestUartBuildPath} ]; then cd ${TestUartBuildPath} #cmake -G "Unix Makefiles" .. cmake .. make clean make # ./Test_uart_Hello ./test_uart cd - # mkdir build_cmake fi <file_sep>#ifndef __SAY_HELLO_07_H__ #define __SAY_HELLO_07_H__ int say_hello07(); #endif <file_sep>#!/bin/bash # run like this export TestBuildPath="./build_cmake" export TestSourcePath="." #cmake3.13 #cmake -B${TestBuildPath} -S${TestSourcePath} cmake -B${TestBuildPath} -H${TestSourcePath} cd ${TestBuildPath} make clean make ./test_run cd - <file_sep>#!/usr/bin/make # #meaning of specific strings #reference info is here: https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables #-------------------------------------------------- #*# $@ The file name of the target of the rule. ‘$@’ is the name of whichever target caused the rule’s recipe # to be run. all of FileNameWithExtension produced # $* all of FileNameWithoutExtension produced # $< the FileName of first dependence item #*# $^ the dependency items with space isolated and remove the repeated item # $+ the dependency items with space isolated, but do not remove the repeated item # $? the dependency items with space isolated, but just have the new item # $| The names of all the order-only prerequisites, with spaces between them #-------------------------------------------------- # $(@D) The directory part of the file name of the target, with the trailing slash removed. # If the value of ‘$@’ is dir/foo.o then ‘$(@D)’ is dir. # This value is . if ‘$@’ does not contain a slash # $(@F) The file-within-directory part of the file name of the target. If the value of ‘$@’ # is dir/foo.o then ‘$(@F)’ is foo.o. ‘$(@F)’ is equivalent to ‘$(notdir $@)’. # $(*D) # $(*F) The directory part and the file-within-directory part of the stem; dir and foo in this example. # $(%D) # $(%F) The directory part and the file-within-directory part of the target archive member name. # This makes sense only for archive member targets of the form archive(member) and is useful # only when member may contain a directory name. (See Archive Members as Targets.) # $(<D) # $(<F) The directory part and the file-within-directory part of the first prerequisite. # $(^D) # $(^F) Lists of the directory parts and the file-within-directory parts of all prerequisites. # $(+D) # $(+F) Lists of the directory parts and the file-within-directory parts of all prerequisites, # including multiple instances of duplicated prerequisites. # $(?D) # $(?F) Lists of the directory parts and the file-within-directory parts of all prerequisites that are newer # than the target. #-------------------------------------------------- #*# % pattern rules, like %.o : %.c #-------------------------------------------------- # Functions for Transforming Text : https://www.gnu.org/software/make/manual/html_node/Functions.html ##### function about string # $(subst <from>,<to>,<text> ) # $(patsubst <pattern>,<replacement>,<text> ) # $(strip <string> ) # $(strip a b c ) # $(findstring <find>,<in> ) # $(filter <pattern...>,<text> ) # $(filter-out <pattern...>,<text> ) # $(sort <list> ) #sort the words of the list in lexical order, removing duplicate words. # $(word <n>,<text> ) # $(word n,text) # $(wordlist s,e,text) # $(words text) # $(firstword names…) # $(lastword names…) #-------------------------------------------------- # https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html ##### function about operation of file name # $(dir <names...> ) # $(notdir <names...> ) # $(suffix <names...> ) # $(basename <names...> ) # $(addsuffix <suffix>,<names...> ) # $(addprefix <prefix>,<names...> ) # $(join <list1>,<list2> ) # $(wildcard pattern) # $(realpath names…) # $(abspath names…) # # $(file op filename[,text]) #-------------------------------------------------- ##### function foreach # $(foreach <var>,<list>,<text> ) #-------------------------------------------------- ##### function conditional # $(if <condition>,<then-part> ) # $(if <condition>,<then-part>,<else-part> ) # $(if condition,then-part[,else-part]) # $(or condition1[,condition2[,condition3…]]) # $(and condition1[,condition2[,condition3…]]) #-------------------------------------------------- ##### function call # $(call <expression>,<parm1>,<parm2>,<parm3>...) #-------------------------------------------------- ##### function origin # $(origin <variable> ) #-------------------------------------------------- # $(value variable) #-------------------------------------------------- ##### function shell # $(shell ls *.c) # files := $(shell ls *.c) #-------------------------------------------------- ##### function control make process # $(error <text ...> ) # $(warning <text ...> ) # $(info <text ...> ) #-------------------------------------------------- ##### rule of Makefile, update a list from a to b # $(var_name:a=b) # $(var_name:.o=.c) # same as # $(patsubst %a ,%b ,var_name) #-------------------------------------------------- # #automatic variables Descriptions #*# $@ The file name of the target # $< The name of the first prerequisite #*# $^ The names of all the prerequisites # $+ Prerequisites listed more than once are duplicated in the order # # define a variable, Var=xx , and the methods of using variable is $(Var) # #search path # VPATH was designed to find sources, not targets. # # VPATH = src include # VPATH %.c src # VPATH %.C src # # VPATH %.cpp src # VPATH %.CPP src # # VPATH %.h include # # VPATH %.cc src # VPATH %.CC src # # VPATH %.s src # VPATH %.S src # #match standard # %.o: %.c # # %.o: %.c # gcc -g -o $@ -c $< # # #.PHONY: all #info#this items is for no dependance item #------------------------------ #CC=gcc #CXX=g++ CC:=clang CXX:=clang++ #------------------------------ #set target name TARGET_EXEC ?= test_run #------------------------------ #set project/code root path PRO_ROOT_PATH = . #TODO#set the build path, the temp file path export BUILD_DIR ?= $(PRO_ROOT_PATH)/build_make $(info "BUILD_DIR is $(BUILD_DIR)") #export $$BUILD_DIR #------------------------------ #TODO#test code SRC_DIRS := $(PRO_ROOT_PATH)/test_main/src #libs code #INC_DIRS := $(shell find $(SRC_DIRS) -type d) #TODO#Add the src by manual #SRC_DIRS += $(PRO_ROOT_PATH)/libs/say_hello/src #SRC_DIRS += $(PRO_ROOT_PATH)/libs/practice/src #Add the src by searching SRC_DIRS += $(shell find ./libs -type d -iname "*src") $(info "SRC_DIRS is $(SRC_DIRS)") #TODO#---------- #shared libs code #get the shared path here #SRC_SHARED_DIRS ?= $(PRO_ROOT_PATH)/libs_shared/shared/src #SRC_SHARED_DIRS ?= $(PRO_ROOT_PATH)/libs_shared SRC_SHARED_DIRS := $(shell find ./libs_shared -type d -iname "*src") $(info "SRC_SHARED_DIRS is $(SRC_SHARED_DIRS)") #log define BUILD_LOG_FILE ?= $(BUILD_DIR)/$(TARGET_EXEC).log #---------- #TODO#share lib name defined TOP_OBJ_SHARED := TestSharedLib.o #$(BUILD_LOG_FILE): # $(MKDIR_P) $(BUILD_DIR) # touch $(BUILD_DIR)/$(TARGET_EXEC).log #all: $(TARGET_EXEC) #------------------------------ #TODO#test code #get source code list for shared lib SRC_SHARED := $(wildcard \ $(SRC_SHARED_DIRS)/*.c \ $(SRC_SHARED_DIRS)/*.cpp) $(info "SRC_SHARED is $(SRC_SHARED)") #get the obj list OBJ_SHARED := $(SRC_SHARED:%=$(BUILD_DIR)/%.o) $(info "OBJ_SHARED is $(OBJ_SHARED)") #ToCheck #include/HeadhFile path for shared lib generating info #INC_DIRS_SHARED := $(PRO_ROOT_PATH)/libs_shared/shared/header INC_DIRS_SHARED := $(shell find $(PRO_ROOT_PATH)/libs_shared -type d -iname header) $(info "INC_DIRS_SHARED is $(INC_DIRS_SHARED)") INC_FLAGS_SHARED := $(addprefix -I,$(INC_DIRS_SHARED)) $(info "INC_FLAGS_SHARED is $(INC_FLAGS_SHARED)") #shared code compile control/argument CFLAGS_SHARED := $(INC_FLAGS_SHARED) -fPIC -shared CPPFLAGS_SHARED := $(INC_FLAGS_SHARED) -fPIC -shared #get the source code list info #SRCS := $(shell find $(SRC_DIRS) -type f -iname *.cpp -or -iname *.c -or -iname *.s) SRCS := $(shell find $(SRC_DIRS) -type f -iname *.cpp -or -iname *.c) $(info "SRCS is $(SRCS)") #get the obj list OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) $(info "OBJS is $(OBJS)") #get the include path #generate the dependency file from .o to .d DEPS := $(OBJS:.o=.d) $(info "DEPS is $(DEPS)") #get the include/Head File path for source code info #INC_DIRS := $(shell find $(SRC_DIRS) -type d -iname header) INC_DIRS := $(shell find $(PRO_ROOT_PATH)/libs -type d -iname header) $(info "INC_DIRS is $(INC_DIRS)") #add test case code path INC_DIRS += $(PRO_ROOT_PATH)/test_main/header \ # $(PRO_ROOT_PATH)/libs/say_hello/header \ # $(PRO_ROOT_PATH)/libs/practice/header #add share code/libs header file path INC_DIRS += $(INC_DIRS_SHARED) #add prefix for compile INC_FLAGS := $(addprefix -I,$(INC_DIRS)) #source code compile control/argument CFLAGS ?= $(INC_FLAGS) -MMD -MP CPPFLAGS ?= $(INC_FLAGS) -MMD -MP #------------------------------ #compile option here ## '-g' mean to generate default debug information for dgb support DEBFLAGS += -g ## '-g0' mean no debug information for dgb support #DEBFLAGS += -g0 ## '-g1' mean minimal debug information for dgb support #DEBFLAGS += -g1 # '-g3' mean maximal debug information for dgb support #DEBFLAGS += -g3 # # for gcc #gcc#DEBFLAGS += -fcallgraph-info #DEBFLAGS += -Wa,-h # -g: Produce debugging information # -Wa,option: Pass option as an option to the assembler # -adhln: # a: turn on listings # d: omit debugging directives # n: omit forms processing # h: include high-level source # l: include assembly # # for clang #issued#DEBFLAGS += -ftrigraphs #issued#DEBFLAGS += -trigraphs #issued#DEBFLAGS += -finstrument-functions # # '-O0' is optimize for faster compilation and build time #DEBFLAGS ?= -O0 # '-O3' is optimize for performance DEBFLAGS ?= -O3 # DebugCompileFlags := #$(DebugCompileFlags) # '-E' means Stop after the preprocessing stage; do not run the compiler proper. #DebugCompileFlags ?= -E # '-S' means Stop after the stage of compilation proper; do not assemble #DebugCompileFlags ?= -S #Attention# '-c' means Compile or assemble the source files, but do not link. #it is not prefer to add this argument into common setting #Attention#DebugCompileFlags += -c # '-save-temps' means Store the usual "temporary" intermediate files permanently; # place them in the current directory and name them based on the source file #it is better to clean before compile with this argument DebugCompileFlags+= -save-temps=obj # # # '-v' means Print (on standard error output) the commands executed to run the stages of compilation. # Also print the version number of the compiler driver program and of the preprocessor # and the compiler proper. #DEBFLAGS ?= -v # '-Omin' is optimize for code size #DEBFLAGS += -Omin # '-Wall' is to enable the all warning #DEBFLAGS += -Wall # '-Werror' is to make all warnings into errors DEBFLAGS += -Werror # '-Wfatal-errors' is to make compile abort when the hit the errors firstly #DEBFLAGS += -Wfatal-errors # #DEBFLAGS ?= -O -g -DSCULL_DEBUG # "-O" is needed to expand inlines #TODO#worked DEBFLAGS += -DPRINT_DEBUG_ENABLE=1 #DEBFLAGS += -DPRINT_DEBUG_ENABLE=0 #------------------------------ #.DEFAULT: compile .DEFAULT: all #TODO set here to select the compile option for shared code/libs style USE_LIBS_LINK=ENABLE_1 #USE_LIBS_LINK=DISABLE_0 DebugLinkFlags := #$(DebugLinkFlags) #CCLDFLAGS_SHARED+= -nostartfiles -Wl,-e,function_shared_test #CCLDFLAGS_SHARED+= -nostartfiles #CCLDFLAGS_SHARED+= -Wl,-Map=$(try_project_name)_output.map $(info "DebugCompileFlags is $(DebugCompileFlags)") #compile : $(BUILD_DIR)/$(TARGET_EXEC) $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED) compile : $(BUILD_DIR)/$(TARGET_EXEC) # $(info "Here get : " $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED)) $(info "Here gen : $(BUILD_DIR)/$(TARGET_EXEC)") #run# $(BUILD_DIR)/$(TARGET_EXEC) #compile: $(BUILD_DIR)/$(TOP_OBJ_SHARED) ifeq ($(USE_LIBS_LINK),ENABLE_1) #========== $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED) $(info "Use the ###libs### to generate target") $(CC) $(OBJS) $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED) $(DEBFLAGS) -o $@ $(CCLDFLAGS_SHARED) ### shared lib, the name of libs is set by manual. $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED): $(SRC_SHARED) $(info "Here gen : " $(BUILD_DIR)/libs_shared/$(TOP_OBJ_SHARED)) $(MKDIR_P) $(dir $@) $(CC) $(SRC_SHARED) $(CFLAGS_SHARED) $(DEBFLAGS) $(DebugCompileFlags) -o $@ ## $(CC) $(CPPFLAGS) $(CFLAGS) $(DEBFLAGS) -c $< -o $@ else #========== #$(BUILD_DIR)/$(TARGET_EXEC): $(BUILD_DIR)/$(OBJS) $(OBJ_SHARED) $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) $(OBJ_SHARED) $(info "Use the ###src### to generate target") $(CC) $(OBJS) $(OBJ_SHARED) $(DEBFLAGS) $(DebugCompileFlags) -o $@ $(LDFLAGS) # $(CXX) $(OBJS) $(OBJ_SHARED) -o $@ $(LDFLAGS) endif # assembly $(BUILD_DIR)/%.s.o : %.s $(MKDIR_P) $(dir $@) $(AS) $(ASFLAGS) -c $< -o $@ # c source #$(BUILD_DIR)/%.c.o: %.c $(BUILD_DIR)/%.c.o: %.c $(MKDIR_P) $(dir $@) $(CC) $(CFLAGS) $(DEBFLAGS) $(DebugCompileFlags) -c $< -o $@ # c++ source $(BUILD_DIR)/%.cpp.o: %.cpp $(MKDIR_P) $(dir $@) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DEBFLAGS) $(DebugCompileFlags) -c $< -o $@ #.PHONY: compile #$(info "run $(BUILD_DIR)/$(TARGET_EXEC)") run: $(info "####################") $(info "run $(BUILD_DIR)/$(TARGET_EXEC) ..........") $(BUILD_DIR)/$(TARGET_EXEC) #.PHONY: run #all : clean $(BUILD_DIR)/$(TARGET_EXEC) #all : clean compile run all : clean compile run #.DEFAULT: all #.PHONY: all .PHONY: clean clean: $(RM) -r $(BUILD_DIR) $(RM) *.o $(RM) *.i $(RM) *.bc $(RM) *.s $(RM) *.map #generate the header dependency file -include $(DEPS) MKDIR_P ?= mkdir -p RM ?= \rm -f <file_sep>#!/bin/bash #TODO# not worked in current status # work flow of Autotools # # (Source code) --autoscan--> (configure.scan) --edit/mv--> (configure.ac/configure.in) # # (configure.ac/configure.in) --aclocal--> (aclocal.m4) # # (configure.ac + aclocal.m4) --autoconf--> configure # (configure.ac/configure.in) --autoheader--> (config.h.in) # (Makefile.am) --automake--> (Makefile.in) # # (Makefile.in + config.h.in + configure) --./configure-->(Makefile) # # # # (configure.ac) --autoconf/autoreconf/autoscan--> (configure.scan) --mv--> (configure.in) # (configure.ac/configure.in) --autoconf--> configure # (configure.ac + Makefile.am) --autoreconf/autoconf/autoscan/automake--> (configure.in + Makefile.in) # (Makefile.in + configure.in) --./configure--> (Makefile) # # 1. autoscan -> (configure.scan + autoscan.log) # 2. mv configure.scan configure.in # 3. # Process this file with autoconf to produce a configure script. # AC_INIT(hello.c) # AM_INIT_AUTOMAKE(ProName, 1.0) # # Checks for programs. # AC_PROG_CC # # Checks for library functions. # AC_OUTPUT(Makefile) # 4. aclocal -> (aclocal.m4 + autom4te.cache) #refer to (configure.in) # 5. autoconf -> (configure) #refer to (configure.in, + aclocal.m4) # 6. edit the Makefile.am # AUTOMAKE_OPTIONS= foreign # bin_PROGRAMS= ExeName # Pro_SOURCES= hello.c # 7. automake --add-missing -> (Makefile.in + depcomp + install-sh + missing) #refer to (configure.in) # 8. ./configure -> (Makefile + config.log + config.status) # #export LDFLAGS="-L/home/songwei/double-conversion/" # #export CPPFLAGS="-I/home/songwei/double-conversion/src/" # #export CFLAGS="-I/home/songwei/double-conversion/src/" # #export LIBS="-ldouble_conversion -ldouble_conversion_pic" # #./configure --prefix=/usr/local/folly # # 1. write the (configure.ac + Makefile.am) # 2. autoreconf -i # 3. Get the (configure + Makefile.in) # 4. ./configure # 5. Get the Makefile # 6. make # 7. Get the target file # 8. make install # #TODO# export TestBuildPath="`pwd`/build_automake" export PathOfSouceCode="`pwd`" #export FileNameOfTopCode="test_main.c" export FileNameOfTopCode="../test_main/src/test_main.c" export FileNameOfExe="test_run" export TimeStampCurrentTryRun="`date +%Y-%m-%d-%H%M`" if [ ! -d ${TestBuildPath} ]; then mkdir -p ${TestBuildPath} fi cd ${TestBuildPath} #------------------------------ #ToCheck#####generate the [configure.ac] file export ConfigureFileName="configure.ac" if [ -f ${ConfigureFileName} ]; then \rm -f ${ConfigureFileName} fi touch ${ConfigureFileName} echo "# Create by ${USER} on ${TimeStampCurrentTryRun}" >> ${ConfigureFileName} #echo "AC_INIT(${FileNameOfTopCode})" >> ${ConfigureFileName} echo "AC_INIT([${FileNameOfTopCode}] ,[1.0] ,[<EMAIL>])" >> ${ConfigureFileName} #echo "AM_INIT_AUTOMAKE([${FileNameOfExe}] ,[1.0])" >> ${ConfigureFileName} echo "AM_INIT_AUTOMAKE([-Wall -Werror foreign])" >> ${ConfigureFileName} # echo "AC_PREREQ(2.5) #AC Version required" >> ${ConfigureFileName} # echo "AC_PROG_CC" >> ${ConfigureFileName} echo "AC_PROG_CXX" >> ${ConfigureFileName} echo "AC_CONFIG_HEADERS(config.h:config.in)" >> ${ConfigureFileName} #echo "AC_CONFIG_HEADERS(config.h)" >> ${ConfigureFileName} #echo "AC_CONFIG_HEADERS(config.h)" >> ${ConfigureFileName} # #echo "AC_OUTPUT(Makefile)" >> ${ConfigureFileName} #add makefile list here with list format echo "AC_CONFIG_FILES([Makefile])" >> ${ConfigureFileName} echo "AC_OUTPUT" >> ${ConfigureFileName} # #debug#echo "AC_CONFIG_SRCDIR(test_main/src/test_main.c)" >> ${ConfigureFileName} #echo "AC_CONFIG_AUX_DIR(config)" >> ${ConfigureFileName} #------------------------------ #ToCheck#####generate the [Makefile.am] file export MakefielAMFileName="Makefile.am" if [ -f ${MakefielAMFileName} ]; then \rm -f ${MakefielAMFileName} fi touch ${MakefielAMFileName} echo "# Create by ${USER} on ${TimeStampCurrentTryRun}" >> ${MakefielAMFileName} echo "AUTOMAKE_OPTIONS = foreign" >> ${MakefielAMFileName} echo "bin_PROGRAMS = test_run" >> ${MakefielAMFileName} echo "files_SOURCES = test_main.c" >> ${MakefielAMFileName} #echo "SUBDIRS = ../test_main/src" >> ${MakefielAMFileName} #------------------------------ #generate configure.scan file autoscan ${PathOfSouceCode} #autoscan -I PathOfIncludeLib ${PathOfSouceCode} # debug # #------------------------------ # debug # #change filename from configure.scan to configure.in # debug # if [ -f ${PathOfSouceCode}/configure.scan ]; then # debug # mv -f ${PathOfSouceCode}/configure.scan ${TestBuildPath}/configure.in # debug # fi # debug # #update the contents of configure.in file according the project # debug # sed -i -r "s/AC_INIT(.*)/AC_INIT(${FileNameOfTopCode}) #ToCheck/g" configure.in # debug # sed -i -r "s/AC_CONFIG_SRCDIR(.*)//g" configure.in # debug # #sed -i -r "s/AC_CONFIG_SRCDIR(.*)/AM_INIT_AUTOMAKE(${FileNameOfExe} ,1.0) #ToCheck/g" configure.in # debug # sed -i -r "s/AC_CONFIG_HEADERS(.*)//g" configure.in # debug # # debug # #AM_INIT_AUTOMAKE(hello, 1.0) # debug # # debug # #AC_CONFIG_SRCDIR([test_main/header/test_main.h]) # debug # #AC_CONFIG_HEADERS([config.h]) # debug # # debug # #sed -i -r "s/AC_CONFIG_FILES(.*)//g" configure.in # debug # #AC_CONFIG_FILES([Makefile]) # debug # #sed -i -r "s/AC_OUTPUT.*/AC_OUTPUT(Makefile) #ToCheck/g" configure.in # debug # #AC_OUTPUT #------------------------------ #TODO#EmacsM configure.in aclocal autoconf touch NEWS #echo "# Create by ${USER} on ${TimeStampCurrentTryRun}" >> NEWS touch README touch AUTHORS touch ChangeLog autoheader #automake #automake -a --add-missing automake --add-missing ./configure #####if [ -d ${TestBuildPath} ]; then ##### cd ${TestBuildPath} ##### #cmake -G "Unix Makefiles" .. ##### cmake .. ##### make clean ##### make ###### ./Test_Hello ##### ./test_run ##### cd - ###### mkdir build_cmake #####fi <file_sep>#Library('',[]) #Library('Test11SharedLib', ['../src_shared/test11_shared.c']) #Library('Test11SharedLib', ['test11_shared.c'] ,CPPPATH=['../include']) #StaticLibrary('Test11SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Library('Test11SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Import('env') Import('*') env.Library('Test11SharedLib' ,Glob('*.c') ,CPPPATH=['../include']) #Program('',[]) #Program('test11' ,['../src/test11.c' ,CPPPATH=['../src' ,'../scr_shared' ,'../include'] ,['../src/say_hello_11.c'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['../src/test11.c' ,'../src/say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) #Program('test11' ,['../src/test11.c' ,'../src/say_hello_11.c'] ,CPPPATH=['../include'] ,LIBS=['Test11SharedLib'] ,LIBPATH=['.']) <file_sep>#ifndef __SAY_HELLO_11_H__ #define __SAY_HELLO_11_H__ int say_hello11(); #endif <file_sep>#include <stdio.h> int say_hello() { printf("hi, test \n"); return 0; } <file_sep>#ifndef __TEST_SETTING_H__ #define __TEST_SETTING_H__ #define PRINT_DEBUG_ENABLE 1 #endif <file_sep># run like this #for gcc make make clean make #./build_gcc/test07 make run #for cmake + make case #cd ./build ##cmake -G "Unix Makefiles" .. #cmake .. #make #./Test07_Hello <file_sep>#include <stdio.h> int say_hello13() { printf("hi, test13 \n"); return 0; } <file_sep>#include <stdio.h> #include "test14.h" //#include "say_hello_14.h" //#include "test14_shared.h" int main(int argc ,char *argv[]) { int value_returned=0; #if PRINT_DEBUG_ENABLE printf("\n"); printf("===================================================\n"); printf("hello test14 \n"); printf("\n"); #endif #if 0 say_hello14(); #endif #if 0 printf("Try to call function_shared_test14(1), get: 0x%x \n" , function_shared_test14(1) ); #endif #if 1 { int i=0; printf("------------------------------\n"); //printf("##### Get argument is %s\n", *argv); printf("##### Get argc is %d\n" , argc); printf("##### Get argv is "); for(i=0;i<argc;i++) { printf(" %s" , argv[i]); } printf("\n"); printf("------------------------------\n"); for(i=0;i<argc;i++) { printf("##### Get argv[%d] is %s\n" ,i ,argv[i]); } } #endif #if 0 { printf("------------------------------\n"); for(i=1;i<argc;) { if ((strcmp (argv[i], "--port") == 0)) { printf("##### get --port info: %s\n", argv[i+1]); } if ((strcasecmp (argv[i], "--file") == 0)) { printf("##### get --file info: %s\n", argv[i+1]); } i=i+2; } } #endif #if 0 { int i, j;//for arg print control //ToCheck //#define MAX_STRING_LENGTH 100 char input_arg_list[][3][MAX_STRING_LENGTH]= //char *input_arg_list[][3]= { {"--port" ,"" ,"set port name info"} ,{"--file" ,"" ,"set file name"} ,{"--end--" ,"--end--" ,"reserved keywords"} }; printf("------------------------------\n"); if ((strcasecmp (argv[1], "--help") == 0)) { printf("##### Help arguments format:\n"); printf("##### --keyword key_value_need_input\n"); printf("##### keyword supported lists:\n"); for (j=0;;j++) { if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list[j][0] ,input_arg_list[j][2]); } //return 1 value_returned =1; } else { for(i=1;i<argc;) { //printf("##### Check argv[%d] info: %s\n" ,i ,argv[i]); for (j=0;;j++) { //printf("##### Check input_arg_list[%d][0] info: %s\n" ,i ,input_arg_list[j][0]); if ((strcasecmp (input_arg_list[j][0], "--end--") == 0)){break;} //if (!strcmp (argv[i], "--file")) if ((strcasecmp (argv[i], input_arg_list[j][0]) == 0)) { //printf("##### get input_arg_list[j][0] info: %s\n", argv[i+1]); //strcpy(input_arg_list[j][1], argv[i+1]); //strncpy(input_arg_list[j][1], argv[i+1] ,MAX_STRING_LENGTH); strncpy(input_arg_list[j][1], argv[i+1] ,strlen(argv[i+1])); printf("##### Get %s info: %s\n" ,input_arg_list[j][0] ,input_arg_list[j][1]); } } i=i+2; } //return 0 value_returned =0; } } #endif #if 1 { //ToCheck //#define MAX_STRING_LENGTH 100 char input_arg_list1[][3][MAX_STRING_LENGTH]= //char *input_arg_list1[][3]= { {"--port" ,"" ,"set port name info"} ,{"--file" ,"" ,"set file name"} ,{"--end--" ,"--end--" ,"reserved keywords"} }; #if 1 //check the argument list contents before updated print_arg_list(input_arg_list1); #endif printf("------------------------------\n"); printf("Start call arg_read function\n"); value_returned = arg_read(argc ,argv ,input_arg_list1); printf("exit arg_read function now\n"); #if 0 int i=0; printf("------------------------------\n"); printf("check the input_arg_list info\n"); for (i=0;;i++) { if ((strcasecmp (input_arg_list1[i][0], "--end--") == 0)){break;} printf("##### %s : %s\n" ,input_arg_list1[i][0] ,input_arg_list1[i][1]); } #endif #if 1 //check the argument list contents updated print_arg_list(input_arg_list1); #endif } #endif #if PRINT_DEBUG_ENABLE printf("\n"); printf("Bye test14 \n"); printf("===================================================\n"); printf("\n"); #endif printf("------------------------------\n"); printf("value_returned is %d\n" ,value_returned); return value_returned; } <file_sep>#ifndef __ARG_READ_H__ #define __ARG_READ_H__ //macro and data type here #define MAX_STRING_LENGTH 100 //function list //int arg_read(char *argv[], char *input_arg_list[][3][MAX_STRING_LENGTH]); int arg_read(int argc ,char *argv[], char input_arg_list[][3][MAX_STRING_LENGTH]); int print_arg_list(char input_arg_list[][3][MAX_STRING_LENGTH]); #endif
3f55464cb01d12ddfa7a35ad6c048ccd25f0005d
[ "CMake", "Markdown", "Makefile", "Python", "Text", "C", "Shell" ]
115
C
qshan/ctest_qshan
13ca45dee9cde3ab8d28dc2d7a707ddd83ade8d7
10c1094d35c9108b402bdea8b47f39790abb7ee1
refs/heads/master
<repo_name>deftomat/opinionated<file_sep>/src/yarn.ts import { bold, underline, yellow } from 'chalk'; import execa from 'execa'; import { existsSync, readFileSync, writeFileSync } from 'fs'; import { fixDuplicates, listDuplicates } from 'yarn-deduplicate'; import { Context } from './context'; import { ToolError } from './errors'; /** * Trows when the `yarn.lock` doesn't match the `node_modules` content. */ export async function checkLockIntegrity(context: Context): Promise<void> { try { await execa('yarn', ['check', '--integrity'], { cwd: context.projectRoot }); } catch (error) { throw new ToolError( 'Integrity check failed with the following errors:', error.stderr, yellow('Error could be caused by an outdated yarn.lock.'), yellow( `Please check that all dependencies are correctly installed by running ${bold( 'yarn install' )}.` ) ); } } /** * Throws when the `yarn.lock` contains dependencies, which can be deduplicated. */ export async function checkLockDuplicates(context: Context): Promise<void> { const duplicates = listDuplicates( readFileSync(`${context.projectRoot}/yarn.lock`).toString(), {} ); if (duplicates.length === 0) return; throw new ToolError( `We found ${duplicates.length} duplicates in yarn.lock file!`, yellow( `Please use ${bold('yarn-deduplicate')} to manually fix these duplicates or run ${bold( 'checkup' )} again with auto-fix enabled.\nSee ${underline( 'https://bit.ly/2QS3FC5' )} for more information.` ) ); } /** * Deduplicate dependencies in `yarn.lock` and run `yarn install` if necessary. * * Use `autoInstall=false` to skip `yarn install`. */ export async function fixLockDuplicates( context: Context, { autoInstall = true } = {} ): Promise<void> { const lockPath = `${context.projectRoot}/yarn.lock`; try { const originalLock = readFileSync(lockPath).toString(); const fixedLock = fixDuplicates(originalLock); if (originalLock !== fixedLock) { writeFileSync(lockPath, fixedLock); if (autoInstall) { await execa('yarn', ['install'], { cwd: context.projectRoot }); } } } catch (error) { throw new ToolError( `Failed to deduplicate dependencies in yarn.lock file!`, yellow( `Please use ${bold('yarn-deduplicate')} to manually fix these duplicates.\nSee ${underline( 'https://bit.ly/2QS3FC5' )} for more information.` ) ); } } /** * Return TRUE, when the given context uses Yarn. */ export function usesYarn(context: Context): boolean { return existsSync(`${context.projectRoot}/yarn.lock`); } <file_sep>/src/eslintRules/organizeImports.ts // TODO: RULE NOT USED YET // Implement auto-fix: // https://eslint.org/docs/developer-guide/working-with-rules#applying-fixes // https://github.com/microsoft/TypeScript/issues/32818 module.exports = { meta: { type: 'problem', docs: { description: 'Specifiers the ordering of import statements', category: 'Stylistic Issues', recommended: 'error' }, messages: { sourceOrder: 'Import sources must be alphabetized.', namedOrder: 'Named imports must be alphabetized.' }, schema: [] }, defaultOptions: [], create(context) { let previousNode: any; return { ImportDeclaration(node) { const localSpecifiers = node.specifiers .filter(specifier => specifier.type === 'ImportSpecifier') .map(specifier => specifier.local); const outOfOrderLocalSpecifiers = spefifiersOutOfOrder(localSpecifiers); if (outOfOrderLocalSpecifiers) { const [first, second] = outOfOrderLocalSpecifiers; context.report({ node, messageId: 'namedOrder', loc: { start: first.loc.start, end: second.loc.end } }); } if (previousNode) { if ( 'value' in node.source && typeof node.source.value === 'string' && 'value' in previousNode.source && typeof previousNode.source.value === 'string' && node.source.value.toUpperCase() < previousNode.source.value.toUpperCase() ) { context.report({ node, messageId: 'sourceOrder', loc: { start: previousNode.loc.start, end: node.loc.end } }); } } previousNode = node; } }; } }; function spefifiersOutOfOrder(specifiers: any) { return pairwise(specifiers).find( ([first, second]) => second.name.toUpperCase() < first.name.toUpperCase() ); } function pairwise(xs: any): any { const pairs: any[] = []; for (let i = 1; i < xs.length; i++) { pairs.push([xs[i - 1], xs[i]]); } return pairs; } <file_sep>/src/git.ts /** * Partially copied from `lint-staged` project. */ import del from 'del'; import execa from 'execa'; import { resolve } from 'path'; import { debug } from './utils'; export type GitWorkflow = ReturnType<typeof createGitWorkflow>; /** * Provides Git related operations. */ export function createGitWorkflow(cwd: string) { let workingCopyTree: any = null; let indexTree: any = null; let formattedIndexTree: any = null; let _gitDir: Promise<string | undefined>; function gitDir() { if (_gitDir === undefined) { // git cli uses GIT_DIR to fast track its response however it might be set to a different path // depending on where the caller initiated this from, hence clear GIT_DIR delete process.env.GIT_DIR; _gitDir = execGit(['rev-parse', '--show-toplevel'], { cwd }).then( path => path, () => undefined ); } return _gitDir; } async function execGit(args, options?) { debug('Running git command', args); try { const { stdout } = await execa('git', args, options); return stdout; } catch (err) { throw new Error(err); } } async function getStagedFiles() { const cwd = await gitDir(); const result = await execGit( ['diff', '--staged', '--diff-filter=ACM', '--name-only', '--relative'], { cwd } ); return result .split('\n') .map(path => path.trim()) .filter(path => path !== '') .map(path => resolve(`${cwd}/${path}`)); } async function writeTree() { return execGit(['write-tree'], { cwd: await gitDir() }); } async function getDiffForTrees(tree1, tree2) { debug(`Generating diff between trees ${tree1} and ${tree2}...`); return execGit( [ 'diff-tree', '--ignore-submodules', '--binary', '--no-color', '--no-ext-diff', '--unified=0', tree1, tree2 ], { cwd: await gitDir() } ); } async function hasPartiallyStagedFiles() { const stdout = await execGit(['status', '--porcelain'], { cwd: await gitDir() }); if (!stdout) return false; const changedFiles = stdout.split('\n'); const partiallyStaged = changedFiles.filter(line => { /** * See https://git-scm.com/docs/git-status#_short_format * The first letter of the line represents current index status, * and second the working tree */ const [index, workingTree] = line; return index !== ' ' && workingTree !== ' ' && index !== '?' && workingTree !== '?'; }); return partiallyStaged.length > 0; } // eslint-disable-next-line async function stashSave() { debug('Stashing files...'); // Save ref to the current index indexTree = await writeTree(); // Add working copy changes to index await execGit(['add', '.'], { cwd: await gitDir() }); // Save ref to the working copy index workingCopyTree = await writeTree(); // Restore the current index await execGit(['read-tree', indexTree], { cwd: await gitDir() }); // Remove all modifications await execGit(['checkout-index', '-af'], { cwd: await gitDir() }); // await execGit(['clean', '-dfx'], options) debug('Done stashing files!'); return [workingCopyTree, indexTree]; } async function updateStash() { formattedIndexTree = await writeTree(); return formattedIndexTree; } async function applyPatchFor(tree1, tree2) { const diff = await getDiffForTrees(tree1, tree2); /** * This is crucial for patch to work * For some reason, git-apply requires that the patch ends with the newline symbol * See http://git.661346.n2.nabble.com/Bug-in-Git-Gui-Creates-corrupt-patch-td2384251.html * and https://stackoverflow.com/questions/13223868/how-to-stage-line-by-line-in-git-gui-although-no-newline-at-end-of-file-warnin */ if (diff) { try { /** * Apply patch to index. We will apply it with --reject so it it will try apply hunk by hunk * We're not interested in failied hunks since this mean that formatting conflicts with user changes * and we prioritize user changes over formatter's */ await execGit( ['apply', '-v', '--whitespace=nowarn', '--reject', '--recount', '--unidiff-zero'], { input: `${diff}\n`, cwd: await gitDir() } ); } catch (err) { debug('Could not apply patch to the stashed files cleanly'); debug(err); debug('Patch content:'); debug(diff); throw new Error('Could not apply patch to the stashed files cleanly.' + err); } } } async function stashPop() { if (workingCopyTree === null) { throw new Error('Trying to restore from stash but could not find working copy stash.'); } debug('Restoring working copy'); // Restore the stashed files in the index await execGit(['read-tree', workingCopyTree], { cwd: await gitDir() }); // and sync it to the working copy (i.e. update files on fs) await execGit(['checkout-index', '-af'], { cwd: await gitDir() }); // Then, restore the index after working copy is restored if (indexTree !== null && formattedIndexTree === null) { // Restore changes that were in index if there are no formatting changes debug('Restoring index'); await execGit(['read-tree', indexTree], { cwd: await gitDir() }); } else { /** * There are formatting changes we want to restore in the index * and in the working copy. So we start by restoring the index * and after that we'll try to carry as many as possible changes * to the working copy by applying the patch with --reject option. */ debug('Restoring index with formatting changes'); await execGit(['read-tree', formattedIndexTree], { cwd: await gitDir() }); try { await applyPatchFor(indexTree, formattedIndexTree); } catch (err) { debug( 'Found conflicts between formatters and local changes. Formatters changes will be ignored for conflicted hunks.' ); /** * Clean up working directory from *.rej files that contain conflicted hanks. * These hunks are coming from formatters so we'll just delete them since they are irrelevant. */ try { const rejFiles = await del(['*.rej']); debug('Deleted files and folders:\n', rejFiles.join('\n')); } catch (delErr) { debug('Error deleting *.rej files', delErr); } } } // Clean up references /* eslint-disable */ workingCopyTree = null; indexTree = null; formattedIndexTree = null; /* eslint-enable */ return null; } async function stageFile(path: string) { return execGit(['add', path], { cwd: await gitDir() }); } async function isGitRepository() { try { await execGit(['rev-parse', '--git-dir']); return true; } catch (error) { return false; } } async function hasChanges(): Promise<boolean> { const changed = await execGit(['status', '-uall', '--porcelain']); return changed.trim() !== ''; } async function ensureMinimumGitVersion(): Promise<void> { const version = await execGit(['--version']); const match = version.match(/([0-9]+).([0-9]+).([0-9]+)/); if (match == null) throw Error('Failed to detect Git version!'); const [, major, minor] = match; if (Number(major) < 2 || (Number(major) === 2 && Number(minor) < 13)) { throw Error('Failed to run! Git >= 2.13.0 is required.'); } } return { stageFile, isGitRepository, stashSave, stashPop, hasPartiallyStagedFiles, updateStash, exec: execGit, getStagedFiles, hasChanges, ensureMinimumGitVersion }; } <file_sep>/index.ts export * from './src/configs'; export * from './src/context'; export * from './src/errors'; export * from './src/eslint'; export * from './src/eslintConfig'; export * from './src/format'; export * from './src/git'; export * from './src/ignore'; export * from './src/preCommit'; export * from './src/typeCheck'; export * from './src/yarn'; <file_sep>/src/utils.ts import { bold, cyan, gray, green, red, yellow } from 'chalk'; import ora from 'ora'; import prettyMs from 'pretty-ms'; import stripAnsi from 'strip-ansi'; import { parentPort, Worker, workerData } from 'worker_threads'; import { MonorepoPackageContext } from './context'; import { ToolError, ToolWarning } from './errors'; export interface StepResult { readonly result?: any; readonly hasWarning: boolean; } export async function step<T>({ description, run, success = description }: { description: string; run: (() => Promise<T>) | (() => T); success?: ((result: T) => string) | string; }): Promise<StepResult> { const spinner = ora({ text: cyan(description) }).start(); await delay(700); try { const startAt = Date.now(); const result = await run(); const endAt = Date.now(); const successText = typeof success === 'function' ? success(result) : success; spinner.stopAndPersist({ symbol: green('✔'), text: green(successText) + gray(` (${prettyMs(endAt - startAt)})`) }); return { result, hasWarning: false }; } catch (error) { if (ToolError.is(error)) { const [first, ...rest] = error.messages; spinner.stopAndPersist({ symbol: red('❌ '), text: red(first) }); rest.forEach(e => console.error(e)); throw process.exit(1); } else if (ToolWarning.is(error)) { const [first, ...rest] = error.messages; spinner.stopAndPersist({ symbol: yellow('⚠️ '), text: yellow(first) }); rest.forEach(e => console.error(e)); return { hasWarning: true }; } else { spinner.stopAndPersist({ symbol: red('❌ '), text: red(description) }); console.error(error); throw process.exit(1); } } } export function delay(time: number) { return new Promise(resolve => setTimeout(resolve, time)); } export function debug(...args: any[]) { if (process.env.DEBUG === 'true') { console.info(...args.map(arg => yellow(arg))); } } export function isNotNil<T>(value: T | null | undefined): value is T { return value != null; } export function populated(value: any): boolean { if (value == null) return false; if (Buffer.isBuffer(value)) return (value as Buffer).length > 0; return value !== ''; } export function renderOnePackageWarning(context: MonorepoPackageContext) { const packageName: string = context.packageSpec.get().name || context.packageRoot.split('/').pop(); const banner = asBanner([ bold(`Running in "${packageName}" sub-package...\n`), `Please keep in mind that to check the whole project,`, `you need to run this command in project's root directory!` ]); console.warn(''); console.warn(yellow.inverse(banner)); console.warn(''); } function asBanner(lines: string[]): string { const normalized = lines.flatMap(line => line.split('\n')).map(line => ` ${line.trim()} `); const maxLength = normalized .map(stripAnsi) .map(line => line.length) .reduce((max, length) => (max > length ? max : length), 0); const content = normalized .map(line => line + spacing(maxLength - stripAnsi(line).length)) .join('\n'); return `${spacing(maxLength)}\n${content}\n${spacing(maxLength)}`; } function spacing(length: number): string { return Array.from(Array(length)).fill(' ').join(''); } export function asWorkerMaster<T extends Function>(workerFilename: string): AlwaysPromiseResult<T> { return ((...args) => { return new Promise((resolve, reject) => { const worker = new Worker(workerFilename, { workerData: args }); worker.on('message', ({ value, error }) => { if (error) { reject(error); } else { resolve(value); } }); worker.on('error', reject); worker.on('exit', code => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }) as any; } export async function runAsWorkerSlave(fn: Function) { if (parentPort == null) throw Error('Unexpected process state!'); try { const value = await fn(...workerData); parentPort.postMessage({ value }); } catch (error) { parentPort.postMessage({ error }); } } type AlwaysPromiseResult<T> = T extends (...args: any[]) => Promise<any> ? T : T extends (...args: infer I) => infer O ? (...args: I) => Promise<O> : never; <file_sep>/CHANGELOG.md # 0.9.0 - feat: stop generating `.nvmrc` file in favor of Volta. # 0.8.1 - fix: disable `strictPropertyInitialization` tsconfig option # 0.8.0 - BREAKING: drop support for Node 12 - feat: TypeScript 4.4 support - fix: disable `react/jsx-key` as it raises false-positive errors in components like this: ```tsx <Dictionary> {[ ['Source', data.articleOne.sources.join(', ')], ['Published', <LocaleDate date={data.articleOne.appearedAt} />] ]} </Dictionary> ``` # 0.7.2 - fix: disable `no-new` ESLint rule because AWS-CDK is breaking this rule extensively # 0.7.1 - fix: reduce cache size # 0.7.0 - feat: major TypeScript, ESLint, YarnDeduplicate and Prettier upgrade # 0.6.6 - feat: allow to use `console.group*` statements # 0.6.5 - feat: always check JS files during TypeScript check # 0.6.4 - fix: warning banner rendering # 0.6.3 - fix: programmatic API # 0.6.2 - feat: export programmatic API for each Opinionated feature - feat: auto install deduplicated dependencies if possible - fix: CPU allocation during TypeScript checks # 0.6.1 - fix: do not add trailing comma during formatting # 0.6.0 - feat: upgrade to Prettier 2.0 - feat: sort package.json entries with `prettier-plugin-package` - fix: step elapsed time # 0.5.9 - fix: do not generate source maps and declaration files during TypeScript checks # 0.5.8 - fix: require Node v12 # 0.5.7 - fix: typo in warning message # 0.5.6 - fix: properly format type check error messages # 0.5.5 - fix: use `array-simple` in `@typescript-eslint/array-type` rule - fix: ensure minimum Git version # 0.5.4 - feat: measure check time - fix: ESLint config - fix: type check performance - fix: better Prettier error handling # 0.5.3 - fix: remove type info support from ESLint # 0.5.2 - fix: fix failing `pre-commit` command - fix: better messages - feat: more TS ESLint rules & type info support # 0.5.1 - fix: specify `typescript` as peer dependency # 0.5.0 A complete rewrite which introduces the new `pre-commit` and `checkup` commands. - feat: remove dependency on `lint-staged` - feat: replace `TSLint` with `ESLint` - feat: create all necessary configs automatically (EditorConfig, Prettier, NVM) - feat: duplicate dependencies check # 0.4.7 - fix: disable integrity check due to multiple false positive warnings # 0.4.6 - fix: enforce `pretty=true` flag to pretty print errors emitted by TypeScript # 0.4.5 - fix: fail on type errors in non-monorepo projects # 0.4.4 - fix: better integrity check error message - bump dependencies # 0.4.3 - support classic non-monorepo projects - make options in `lint-staged.config.js - createConfig()` required # 0.4.2 - support `tsconfig.base.json` - make TSC optional - added new flag `--with-tsc` # 0.4.1 - remove node_modules verification as it is broken in Yarn workspaces - replace deprecated `no-unnecessary-bind` by build-in `unnecessary-bind` TSLint rule # 0.4.0 Provides a fully featured pre-commit command which will run the following checks: - check yarn.lock integrity - check dependencies tree - check all TypeScript packages for TS errors - lint and format all staged files # 0.3.10 - upgraded dependencies - NVM support - TSConfig: `jsx": "preserve"` - TSConfig: absolute path in `extends` property (requires TS v3.2) # 0.3.9 - TSLint: improved `early-exit` rule. - TSLint: added `deprecation` warning. # 0.3.8 - TSLint: exclude `node_modules` - Prettier: HTML, MDX support # 0.3.5 - TSConfig - Move `noEmit` from base config to templates. # 0.3.4 - TSLint - Removed `no-unbound-method` rule. - Removed `no-inferred-empty-object-type` rule. # 0.3.3 - TSLint - Removed `array-type` rule. # 0.3.2 - TSConfig - Base config now contains only style related options. # 0.3.1 - TSConfig - Removed `jsx` option. - Monorepo: - Show report after type-check # 0.3.0 - TSConfig: - Added base config - TSLint: - Added `object-literal-shorthand` rule - Monorepo: - Added `wsrun` and example scripts object # 0.2.3 - TSConfig: - Added `"allowSyntheticDefaultImports": true` # 0.2.2 - TSLint rules: - Removed `strict-type-predicates` rule. - Removed `ban-keywords` from `variable-name` rule. # 0.2.1 - React support: - Added `jsx` to `tsconfig.json`. - Additional TSLint rules: `jsx-boolean-value`, `jsx-key` - Removed deprecated TSLint rules: - `no-unused-variable` # 0.2.0 - first release <file_sep>/src/cleanup.ts export const onProcessExit = new Set<Function>(); export function registerExitHandlers() { const cleanup = async () => { await Promise.all([...onProcessExit].map(fn => fn())); process.exit(); }; process.on('SIGINT', cleanup); process.on('SIGUSR1', cleanup); process.on('SIGUSR2', cleanup); process.on('uncaughtException', error => { console.error('UNCAUGHT EXCEPTION!'); console.error(error); return cleanup; }); process.on('unhandledRejection', error => { console.error('UNHANDLED REJECTION!'); console.error(error); return cleanup; }); } <file_sep>/src/typeCheck.ts import { bold, red, yellow } from 'chalk'; import { createHash } from 'crypto'; import execa from 'execa'; import fs from 'fs'; import { Context, isMonorepoContext, MonorepoContext, MonorepoPackageContext, PackageContext } from './context'; import { allocateCore } from './cpu'; import { ToolError } from './errors'; // TODO: Use source files instead of builded files in monorepos! // Otherwise, your monorepo could contains an outdated build of package and // any other package which depends on it will be type checked against this outdated declarations. /** * Return TRUE when the given context contains `tsconfig.json` file. */ export function containsTypeScript(context: Context): boolean { if (isMonorepoContext(context)) return getTypeScriptPackages(context.packagesPath).length > 0; return isTypeScriptPackage({ path: context.packageRoot }); } /** * Runs TypeScript checks in the given context. */ export async function runTypeCheck(context: Context): Promise<void> { if (isMonorepoContext(context)) return runTscInAllPackages(context); return runTscInPackage(context); } async function runTscInPackage(context: PackageContext | MonorepoPackageContext) { const { packageRoot } = context; if (!isTypeScriptPackage({ path: packageRoot })) return; const result = await withTscResult(context)({ path: packageRoot }); if (!hasError(result)) return; throw new ToolError(red(`Checkup failed with the following TypeScript errors:\n`), result.stdout); } async function runTscInAllPackages(context: MonorepoContext) { const { packagesPath } = context; const packages = getTypeScriptPackages(packagesPath).map(withTscResult(context)); const results = await Promise.all(packages); if (!results.some(hasError)) return; const { length } = results.filter(hasError); const header = length === 1 ? red(`1 package failed with the following TypeScript errors:`) : red(`${length} packages failed with the following TypeScript errors:`); const formatted = results .filter(hasError) .map(({ name, stdout }) => { const decorationLength = 76; const decoration = new Array(decorationLength).fill('=').join(''); const spacing = new Array(Math.round((decorationLength - name.length - 8) / 2)) .fill(' ') .join(''); return yellow(`\n${decoration}\n${spacing}Package ${bold(name)}\n${decoration}\n\n`) + stdout; }) .join(''); throw new ToolError(header, formatted); } function withTscResult(context: Context) { const { projectRoot, cachePath } = context; const binPath = `${projectRoot}/node_modules/.bin/tsc`; return async pkg => { const thread = await allocateCore(); const outDir = `${cachePath}/tsc/${createHash('sha1') .update(pkg.path) .digest() .toString('hex')}`; try { await execa( binPath, [ '--allowJs', '--checkJs', '--noEmit', 'true', '--outDir', outDir, '--incremental', '--allowUnreachableCode', 'false', '--pretty', '--noUnusedLocals', '--removeComments', '--sourceMap', '--declarationMap', 'false', '--diagnostics', 'false', '--assumeChangesOnlyAffectDirectDependencies', 'false' ], { cwd: pkg.path } ); return { ...pkg, stdout: null }; } catch (error) { return { ...pkg, stdout: error.stdout }; } finally { thread.free(); } }; } function getTypeScriptPackages(packagesPath: string) { return fs.readdirSync(packagesPath).map(toPackage(packagesPath)).filter(isTypeScriptPackage); } function hasError({ stdout }) { return stdout != null; } function toPackage(packagesPath: string) { return name => ({ name, path: `${packagesPath}/${name}` }); } function isTypeScriptPackage({ path }: { path: string }) { return fs.existsSync(`${path}/tsconfig.json`); } <file_sep>/cli.ts import { bold, gray, red, yellow } from 'chalk'; import program from 'commander'; import inquirer from 'inquirer'; import { registerExitHandlers } from './src/cleanup'; import { ensureConfigs } from './src/configs'; import { Context, describeContext, isMonorepoPackageContext } from './src/context'; import { lint } from './src/eslint'; import { format } from './src/format'; import { preCommit } from './src/preCommit'; import { getIncompleteChecks, updateIncompleteChecks } from './src/store'; import { containsTypeScript, runTypeCheck } from './src/typeCheck'; import { renderOnePackageWarning, step, StepResult } from './src/utils'; import { checkLockDuplicates, checkLockIntegrity, fixLockDuplicates, usesYarn } from './src/yarn'; // eslint-disable-next-line const { version, description } = require('../../package.json'); registerExitHandlers(); program.version(version, '-v, --vers', 'output the current version').description(description); program.command('pre-commit').description('Run pre-commit checks.').action(handlePreCommit); program.command('checkup').description('Check up the project.').action(handleCheckup); program .command('ensure-configs') .description( 'Ensure that all necessary configs are in place.\n\n' + 'In a normal conditions, running this command is not necessary as \neach check ensures that all configs are in place.' ) .action(handleEnsureConfigs); program.on('command:*', () => { console.error( red('Invalid command: %s\nSee --help for a list of available commands.'), program.args.join(' ') ); }); program.parse(process.argv); if (!process.argv.slice(2).length) { program.outputHelp(red); } async function handlePreCommit(cmd) { const context = await prepareContext({ autoStage: true }); await step({ description: 'Running pre-commit checks', run: () => preCommit(context) }); } async function handleCheckup(cmd) { const context = await prepareContext({ autoStage: false }); if (isMonorepoPackageContext(context)) renderOnePackageWarning(context); const incompleteChecks = getIncompleteChecks(context); const { requiredChecks, autoFix } = await inquirer.prompt([ { type: 'checkbox', name: 'requiredChecks', message: 'Select checkup operations:', choices: [ usesYarn(context) && { checked: incompleteChecks.size > 0 ? incompleteChecks.has('integrity') : true, name: `${bold('Integrity')} - ensures that dependencies are installed properly`, short: 'Integrity', value: 'integrity' }, usesYarn(context) && { checked: incompleteChecks.size > 0 ? incompleteChecks.has('duplicates') : true, name: `${bold( 'Dependency duplicates check' )} - ensures no unnecessary dependency duplicates`, short: 'Duplicates', value: 'duplicates' }, { checked: incompleteChecks.size > 0 ? incompleteChecks.has('eslint') : true, name: `${bold('Linter')} - runs ESLint`, short: 'Linter', value: 'eslint' }, containsTypeScript(context) && { checked: incompleteChecks.size > 0 ? incompleteChecks.has('typescript') : true, name: `${bold('TypeScript check')} - detects type errors and unused code`, short: 'TypeScript', value: 'typescript' }, { checked: incompleteChecks.size > 0 ? incompleteChecks.has('prettier') : false, name: `${bold('Formatting')} - runs Prettier`, short: 'Formatter', value: 'prettier' } ].filter(Boolean) }, { type: 'confirm', name: 'autoFix', message: 'Do you want to auto-fix any issues if possible?', default: false, when: ({ requiredChecks }) => requiredChecks.includes('eslint') || requiredChecks.includes('duplicates') } ]); if ((await context.git.hasChanges()) && (autoFix || requiredChecks.includes('prettier'))) { const { shouldRun } = await inquirer.prompt([ { type: 'confirm', name: 'shouldRun', message: yellow( 'Selected operations may affect your non-committed files! Do you want to continue?' ), default: false } ]); if (!shouldRun) process.exit(); } updateIncompleteChecks(context, requiredChecks); const checks: Check[] = []; checks.push({ name: 'integrity', enabled: requiredChecks.includes('integrity'), description: 'Checking yarn.lock integrity', run: () => checkLockIntegrity(context) }); checks.push({ name: 'duplicates', enabled: requiredChecks.includes('duplicates') && autoFix, description: 'Removing dependency duplicates', run: () => fixLockDuplicates(context) }); checks.push({ name: 'duplicates', enabled: requiredChecks.includes('duplicates') && !autoFix, description: 'Detecting dependency duplicates', run: () => checkLockDuplicates(context) }); checks.push({ name: 'eslint', enabled: requiredChecks.includes('eslint') && autoFix, description: 'Linting & auto-fixing via ESLint', run: () => lint(context, { autoFix: true }) }); checks.push({ name: 'eslint', enabled: requiredChecks.includes('eslint') && !autoFix, description: 'Linting via ESLint', run: () => lint(context, { autoFix: false }) }); checks.push({ name: 'typescript', enabled: requiredChecks.includes('typescript'), description: 'Running TypeScript checks', run: () => runTypeCheck(context) }); checks.push({ name: 'prettier', enabled: requiredChecks.includes('prettier'), description: 'Formatting with Prettier', run: () => format(context) }); const missingChecks = new Set<string>(requiredChecks); for (const check of checks) { if (!check.enabled) continue; check.result = await step({ description: check.description, run: check.run }); missingChecks.delete(check.name); updateIncompleteChecks(context, missingChecks); } } interface Check { readonly name: string; readonly enabled: boolean; readonly description: string; result?: StepResult; run(): void; } async function handleEnsureConfigs(cmd) { const context = describeContext(process.cwd()); await step({ description: 'Checking necessary configs', run: () => ensureConfigs(context), success: (addedConfigs: string[]) => { if (addedConfigs.length > 0) { return `The following configs have been added into project: ${addedConfigs.join(', ')}`; } return 'All configs are in place'; } }); } async function prepareContext({ autoStage }: { autoStage: boolean }): Promise<Context> { try { const context = describeContext(process.cwd()); await context.git.ensureMinimumGitVersion(); if (!(await context.git.isGitRepository())) { throw Error('Failed to run! Project must be the Git repository.'); } const addedConfigs = await ensureConfigs(context, { autoStage }); if (addedConfigs.length > 0) console.info( gray(`[The following configs have been added into project: ${addedConfigs.join(', ')}]`) ); return context; } catch (e) { console.error(red(e.message)); throw process.exit(1); } } <file_sep>/src/errors.ts /** * Represents an fatal error raised by tool. * * `ToolError` should be handled and app should fail immediately. */ export class ToolError extends Error { readonly messages: string[]; constructor(...messages: string[]) { super(messages.join('\n')); Error.captureStackTrace(this, ToolError); this.messages = messages; } static is(error: any): error is ToolError { return error instanceof ToolError; } } /** * Represents an warning raised by tool. * * `ToolWarning` should be handled and app should continue with warnings. */ export class ToolWarning extends Error { readonly messages: string[]; constructor(...messages: string[]) { super(messages.join('\n')); Error.captureStackTrace(this, ToolWarning); this.messages = messages; } static is(error: any): error is ToolWarning { return error instanceof ToolWarning; } } <file_sep>/src/context.ts import { bold, red } from 'chalk'; import findUp from 'find-up'; import fs from 'fs'; import path from 'path'; import { ToolError } from './errors'; import { createGitWorkflow, GitWorkflow } from './git'; export type Context = MonorepoContext | MonorepoPackageContext | PackageContext; export interface MonorepoContext { readonly type: 'monorepo'; readonly projectRoot: string; readonly projectSpec: SpecConnector; readonly packagesPath: string; readonly packageRoot: undefined; readonly packageSpec: undefined; readonly cachePath: string; readonly git: GitWorkflow; } export interface MonorepoPackageContext { readonly type: 'monorepo-package'; readonly projectRoot: string; readonly projectSpec: SpecConnector; readonly packagesPath: string; readonly packageRoot: string; readonly packageSpec: SpecConnector; readonly cachePath: string; readonly git: GitWorkflow; } export interface PackageContext { readonly type: 'package'; readonly projectRoot: string; readonly projectSpec: SpecConnector; readonly packagesPath: undefined; readonly packageRoot: string; readonly packageSpec: SpecConnector; readonly cachePath: string; readonly git: GitWorkflow; } export function isMonorepoContext(context: Context): context is MonorepoContext { return context.type === 'monorepo'; } export function isMonorepoPackageContext(context: Context): context is MonorepoPackageContext { return context.type === 'monorepo-package'; } export function isPackageContext(context: Context): context is PackageContext { return context.type === 'package'; } /** * Returns the tool context for the given working directory. */ export function describeContext(cwd: string): Context { try { const specConnector = toSpecConnector(`${cwd}/package.json`); const spec = specConnector.get(); const packageContext: PackageContext = { type: 'package', projectRoot: cwd, projectSpec: specConnector, packagesPath: undefined, packageRoot: cwd, packageSpec: specConnector, cachePath: toCachePath(cwd), git: createGitWorkflow(cwd) }; if (spec.workspaces) { const context: MonorepoContext = { type: 'monorepo', projectRoot: cwd, projectSpec: specConnector, packagesPath: `${cwd}/packages`, packageRoot: undefined, packageSpec: undefined, cachePath: toCachePath(cwd), git: createGitWorkflow(cwd) }; return context; } const parent = findUp.sync('package.json', { cwd: `${cwd}/../` }); if (parent == null) return packageContext; const parentSpecConnector = toSpecConnector(parent); const parentSpec = parentSpecConnector.get(); if (parentSpec.workspaces) { const parentRoot = path.dirname(parent); const context: MonorepoPackageContext = { type: 'monorepo-package', projectRoot: parentRoot, projectSpec: parentSpecConnector, packagesPath: `${parentRoot}/packages`, packageRoot: cwd, packageSpec: specConnector, cachePath: toCachePath(parentRoot), git: createGitWorkflow(parentRoot) }; return context; } return packageContext; } catch (error) { if (error.code === 'ENOENT') { throw new ToolError( red( `No ${bold( 'package.json' )} found! Please make sure that you run this command in the root of JS/TS project.` ) ); } throw Error(`Unexpected error:\n${error}`); } } interface SpecConnector { readonly path: string; get(): any; set(content: string): void; } function toSpecConnector(path: string): SpecConnector { return { path, get() { return JSON.parse(fs.readFileSync(path).toString()); }, set(content: string) { fs.writeFileSync(path, JSON.stringify(content, null, 2)); } }; } function toCachePath(projectRoot: string): string { return `${projectRoot}/node_modules/.cache/opinionated`; } <file_sep>/src/eslint.ts import { CLIEngine } from 'eslint'; import { isMainThread } from 'worker_threads'; import { Context } from './context'; import { ToolError, ToolWarning } from './errors'; import { checkupLintConfig } from './eslintConfig'; import { defaultIgnorePattern, findEslintIgnoreFile } from './ignore'; import { asWorkerMaster, runAsWorkerSlave } from './utils'; /** * Runs a full lint on a given project. * * If a context defines a specific sub-package of a monorepo, * then ESLint will run only in that sub-package. */ export async function lint( context: Context, { autoFix = false }: { autoFix?: boolean } = {} ): Promise<void> { try { const runEslint = asWorkerMaster<typeof getEslintReport>(__filename); const { results, errorCount, warningCount } = await runEslint({ ignorePath: findEslintIgnoreFile(context), cachePath: context.cachePath, projectRoot: context.projectRoot, packageRoot: context.packageRoot, autoFix }); if (errorCount === 0 && warningCount === 0) return; const formatter = CLIEngine.getFormatter('stylish'); const formattedReport = formatter(results); if (errorCount === 0) { throw new ToolWarning( `We found a minor ESLint warnings. We recommend you to fix them as soon as possible:`, formattedReport ); } throw new ToolError(`ESLint failed with the following errors:`, formattedReport); } catch (error) { if (error.messageTemplate === 'file-not-found') return; if (error.messageTemplate === 'all-files-ignored') return; throw error; } } if (!isMainThread) { runAsWorkerSlave(getEslintReport); } function getEslintReport({ ignorePath, cachePath, projectRoot, packageRoot, autoFix }: { ignorePath: string | undefined; cachePath: string; projectRoot: string; packageRoot: string | undefined; autoFix: boolean; }) { const linter = new CLIEngine({ ignore: true, ignorePath, useEslintrc: true, ignorePattern: defaultIgnorePattern, cache: true, cacheLocation: `${cachePath}/checkup-eslintcache`, cwd: projectRoot, fix: autoFix, baseConfig: checkupLintConfig }); const report = linter.executeOnFiles([`${packageRoot || projectRoot}/**/*.?(js|jsx|ts|tsx)`]); if (autoFix) CLIEngine.outputFixes(report); return report; } <file_sep>/src/format.ts import execa from 'execa'; import { Context } from './context'; import { ToolError } from './errors'; import { findPrettierIgnoreFile } from './ignore'; import { populated } from './utils'; // TODO: Add cache support: https://github.com/prettier/prettier/issues/6577 // Make sure that new Prettier version or different Prettier config will invalidate cache. /** * Formats all supported files in the given context. */ export async function format(context: Context): Promise<void> { const { projectRoot, packageRoot } = context; const binPath = `${projectRoot}/node_modules/.bin/prettier`; const ignorePath = findPrettierIgnoreFile(context); const target = `${ packageRoot || projectRoot }/**/*.?(js|jsx|ts|tsx|html|css|scss|json|yml|graphql|md|mdx|gql)`; try { const ignoreOption = ignorePath ? ['--ignore-path', ignorePath] : []; await execa(binPath, ['--write', target, ...ignoreOption], { cwd: projectRoot }); } catch (error) { throw new ToolError( 'We were unable to format your codebase! Prettier failed with the following error:', populated(error.stderr) ? error.stderr : error.stdout ); } } <file_sep>/README.md <h1 align="center">Opinionated 🙏</h1> <h3 align="center">Opinionated tooling for JavaScript & TypeScript projects.</h3> ## Why? Because orchestrating all the tools, linters, formatters, etc. in each project can took a long time and their configuration will differ more and more as you will copy it between multiple projects. **Opinionated** provides everything in one place and upgrading your tool chain is as easy as upgrading the dependency version. ## Installation ``` $ yarn add @deftomat/opinionated --dev ``` ## Usage Tool provides the following commands: ### > Pre-commit ``` $ opinionated pre-commit ``` Pre-commit command will try to run simple, auto-fixable operations on staged files. Operations includes common ESLint rules, Prettier, etc. Command is designed to be opaque and hassle free, so theoretically, pre-commit check should pass for 99% of commits without any error or warning. ### > Checkup ``` $ opinionated checkup ``` Checkup command allows you to keep your project in top shape. Command includes: - **Engine check** - Ensures that you are using the right NodeJS version. - **Integrity** - (yarn only) Ensures that dependencies are installed properly. - **Dependency duplicates check** - (yarn only) Ensures no unnecessary dependency duplicates. Especially useful for monorepos. - **Linter** - Strict ESLint rules. - **TypeScript check** - Detects type errors and unused code. - **Formatting** - Runs Prettier. Command is aware of _yarn workspaces_ and is able to run checks on whole monorepo or just in one package. To run checks in all packages, just run it in project's root. To run checks in one package, you need to run it in package's directory. > 💡 We recommend to run this command before pull requests and deployments. ### > Ensure configs ``` $ opinionated ensure-configs ``` Command will add the following configs if necessary: - [EditorConfig](https://editorconfig.org/) - Makes sure that every developer use the same indentation, charset, EOF, etc. - [Prettier](https://prettier.io/) - Makes sure that every supported editor use the same auto-formatting rules. > 💡 This command is usually not necessary as every other command runs it by default. ## Integration into project To integrate the tool into your project, we recommend the following `packages.json`: ``` { ... "scripts": { "checkup": "opinionated checkup" }, "husky": { "hooks": { "pre-commit": "opinionated pre-commit" } }, "devDependencies": { "@deftomat/opinionated": "^0.6.0", "husky": "^4.0.0" } ... } ``` This configuration allows you to automatically run _pre-commit_ check before each commit (via [Husky](https://github.com/typicode/husky) git hook) and provides `yarn checkup` to easily run _checkup_ command. ## Custom ESLint rules If you need to alter the predefined ESLint rules, just follow the [ESLint configuration guide](https://eslint.org/docs/user-guide/configuring). Any rule specified in your configuration file will be merged over build-in configuration. This allows you to add/edit/remove any rule you want. ## Ignoring files and directories As tool is using ESLint and Prettier, you can follow their guidelines to ignore any file or directory. However, when tool detects, that there are no _.ignore_ file for these tools, then it tries to use `.opinionatedignore` file which will be applied to both ESLint and Prettier. If there is no `.opinionatedignore`, then `.gitignore` will be used. **Resolution order for ESLint:** - `.eslintignore` - `eslintIgnore` property in `package.json` - `.opinionatedignore` - `.gitignore` **Resolution order for Prettier:** - `.prettierignore` - `.opinionatedignore` - `.gitignore` <file_sep>/configs/examples.md **.gitignore:** ``` .idea .vscode/* !.vscode/extensions.json !.vscode/launch.json !.vscode/tasks.json node_modules yarn-error.log __diff_output__ coverage .serverless dist build *.tsbuildinfo .DS_Store ``` **tsconfig.json:** ``` { "extends": "@deftomat/opinionated/configs/tsconfig.json", "compilerOptions": { "baseUrl": "./", "isolatedModules": true, "lib": ["ES2020"], "jsx":"preserve", "module": "ESNext", "moduleResolution": "node", "noEmit": true, "skipLibCheck": true, "sourceMap": true, "target": "ES2020" }, "exclude": [ "**/node_modules/", "**/build/", "**/coverage/", "**/.serverless/" ], } ``` **package.json:** ``` { "name": "<NAME>", "version": "0.1.0", "private": true, "engines": { "node": ">=12.0.0" }, "scripts": { "checkup": "opinionated checkup" }, "dependencies": {}, "devDependencies": { "@deftomat/opinionated": "<PKG_VERSION>", "husky": "^4.0.0" }, "husky": { "hooks": { "pre-commit": "opinionated pre-commit" } }, "workspaces": [ "packages/*" ] } ``` <file_sep>/src/configs.ts import fs from 'fs'; import { Context } from './context'; /** * Ensures that project has the necessary configs in place. */ export function ensureConfigs( context: Context, { autoStage = false }: { autoStage?: boolean } = {} ): Promise<string[]> { return Promise.all([ ensureEditorConfig(context, autoStage), ensurePrettierConfig(context, autoStage) // ensureEslintConfig(context, autoStage), ]).then(results => results.filter(isString)); } function isString(value: string | undefined): value is string { return typeof value === 'string'; } async function ensureEditorConfig( context: Context, autoStage: boolean ): Promise<string | undefined> { const { projectRoot, git } = context; const configPath = `${projectRoot}/.editorconfig`; if (!fs.existsSync(configPath)) { fs.writeFileSync(configPath, defaultEditorConfig); if (autoStage) await git.stageFile(configPath); return 'EditorConfig'; } } async function ensurePrettierConfig( context: Context, autoStage: boolean ): Promise<string | undefined> { const { projectRoot, projectSpec, git } = context; const possibleConfigFiles = [ '.prettierrc', '.prettierrc.yaml', '.prettierrc.yml', '.prettierrc.json', '.prettierrc.toml', '.prettierrc.js', 'prettier.config.js' ]; const spec = projectSpec.get(); const hasConfig = spec.prettier != null || possibleConfigFiles.some(filename => fs.existsSync(`${projectRoot}/${filename}`)); if (!hasConfig) { projectSpec.set({ ...spec, prettier: '@deftomat/opinionated/configs/prettier.config.js' }); if (autoStage) await git.stageFile(projectSpec.path); return 'Prettier'; } } // NOT ENABLED YET // async function ensureEslintConfig( // context: Context, // autoStage: boolean // ): Promise<string | undefined> { // const { projectRoot, projectSpec, git } = context; // const possibleConfigFiles = [ // '.eslintrc', // '.eslintrc.yaml', // '.eslintrc.yml', // '.eslintrc.json', // '.eslintrc.toml', // '.eslintrc.js', // 'eslintrc.config.js' // ]; // const spec = projectSpec.get(); // const hasConfig = // spec.eslintConfig != null || // possibleConfigFiles.some(filename => fs.existsSync(`${projectRoot}/${filename}`)); // if (!hasConfig) { // projectSpec.set({ // ...spec, // eslintConfig: { extends: ['./node_modules/@deftomat/opinionated/configs/eslint'] } // }); // if (autoStage) await git.stageFile(projectSpec.path); // return 'ESLint'; // } // } const defaultEditorConfig = `# http://EditorConfig.org [*] charset = utf-8 end_of_line = lf indent_size = 2 indent_style = space insert_final_newline = true trim_trailing_whitespace = true `; <file_sep>/tsconfig.json { "extends": "./configs/tsconfig.json", "compilerOptions": { "lib": ["ES2020"], "module": "ESNext", "moduleResolution": "node", "skipLibCheck": true, "sourceMap": false, "target": "ES2019", "outDir": "./dist/esm", "declaration": true }, "exclude": ["node_modules", "./configs", "./dist", "./bin"] } <file_sep>/src/ignore.ts import fs from 'fs'; import { Context } from './context'; /** * Returns filename of ignore file for ESLint. */ export function findEslintIgnoreFile({ projectRoot, projectSpec }: Context): string | undefined { const eslintIgnore = `${projectRoot}/.eslintignore`; const opinionatedIgnore = `${projectRoot}/.opinionatedignore`; const gitIgnore = `${projectRoot}/.gitignore`; if (fs.existsSync(eslintIgnore)) return eslintIgnore; if (projectSpec.get().eslintIgnore != null) return; if (fs.existsSync(opinionatedIgnore)) return opinionatedIgnore; if (fs.existsSync(gitIgnore)) return gitIgnore; } /** * Returns filename of ignore file for Prettier. */ export function findPrettierIgnoreFile({ projectRoot }: Context): string | undefined { const prettierIgnore = `${projectRoot}/.prettierignore`; const opinionatedIgnore = `${projectRoot}/.opinionatedignore`; const gitIgnore = `${projectRoot}/.gitignore`; if (fs.existsSync(prettierIgnore)) return prettierIgnore; if (fs.existsSync(opinionatedIgnore)) return opinionatedIgnore; if (fs.existsSync(gitIgnore)) return gitIgnore; } export const defaultIgnorePattern = '**/node_modules/'; <file_sep>/configs/eslint.js const { editorLintConfig } = require('../dist/src/eslintConfig'); module.exports = editorLintConfig; <file_sep>/src/preCommit.ts import { bold, red } from 'chalk'; import { CLIEngine } from 'eslint'; import { promises as fs } from 'fs'; import prettier from 'prettier'; import { onProcessExit } from './cleanup'; import { Context } from './context'; import { ToolError } from './errors'; import { preCommitLintConfig } from './eslintConfig'; import { defaultIgnorePattern, findEslintIgnoreFile, findPrettierIgnoreFile } from './ignore'; import { isNotNil } from './utils'; /** * Runs pre-commit operations on staged files. */ export async function preCommit(context: Context): Promise<void> { const { git } = context; const staged = await git.getStagedFiles(); if (staged.length === 0) return; const hasPartiallyStagedFiles = await git.hasPartiallyStagedFiles(); if (hasPartiallyStagedFiles) await git.stashSave(); const cleanup = hasPartiallyStagedFiles ? () => git.stashPop() : () => null; onProcessExit.add(cleanup); const linter = createLinter(context); const processed = await Promise.all(staged.map(processFile({ context, linter }))); const errors = processed.filter(isNotNil); const hasError = errors.length > 0; if (hasPartiallyStagedFiles && !hasError) await git.updateStash(); onProcessExit.delete(cleanup); await cleanup(); if (hasError) { throw new ToolError( 'Pre-commit checks failed with the following errors:', ...errors.map(e => `${e}\n`) ); } } /** * Returns `undefined` when a given file processed with no errors. * * Otherwise, returns `Error` when a given file cannot be processed. */ function processFile({ context, linter }: { context: Context; linter: CLIEngine }) { return async (filename: string): Promise<string | undefined> => { try { const prettierFileInfo = await prettier.getFileInfo(filename, { ignorePath: findPrettierIgnoreFile(context) }); const { inferredParser } = prettierFileInfo; if (inferredParser == null) return; const shouldPrettify = !prettierFileInfo.ignored; const shouldLint = !linter.isPathIgnored(filename) && (inferredParser === 'babel' || inferredParser === 'typescript'); if (!shouldPrettify && !shouldLint) return; const original = (await fs.readFile(filename)).toString(); if (original.trim() === '') return; let content = original; if (shouldLint) { const { errorCount, warningCount, results } = linter.executeOnText(content, filename); if (errorCount !== 0 || warningCount !== 0) { return linter.getFormatter('stylish')(results); } content = results[0].output || content; } if (shouldPrettify) { try { const options = await prettier.resolveConfig(filename, { editorconfig: true }); content = prettier.format(content, { ...options, parser: inferredParser }); } catch (error) { return red(`Failed to run Prettier on ${bold(filename)}!\n`) + error; } } if (original !== content) { await fs.writeFile(filename, content); await context.git.stageFile(filename); } } catch (error) { return error.toString(); } }; } function createLinter(context: Context): CLIEngine { return new CLIEngine({ ignore: true, ignorePath: findEslintIgnoreFile(context), useEslintrc: false, ignorePattern: defaultIgnorePattern, cwd: context.projectRoot, fix: true, baseConfig: preCommitLintConfig }); } <file_sep>/src/eslintConfig.ts /** * ⚠️ !!!STOP: ESSENTIAL RULES MUST BE AUTOFIXABLE !!! ⚠️ * When adding rules here, you need to make sure they are compatible with * `typescript-eslint`, as some rules such as `no-array-constructor` aren't compatible. */ const essentialRules = { 'react/jsx-boolean-value': 'error', 'react/jsx-fragments': ['error', 'syntax'], // 'opinionated/organize-imports': 'error', 'no-else-return': 'error', 'no-implicit-coercion': 'error', 'no-undef-init': 'error', // 'multiline-comment-style': 'error', 'no-lonely-if': 'error', 'no-unneeded-ternary': 'error', 'no-useless-computed-key': 'error', 'no-useless-rename': 'error', 'no-var': 'error', 'object-shorthand': 'error', 'no-regex-spaces': 'error', 'spaced-comment': ['error', 'always', { exceptions: ['-', '+', '=', '*'], markers: ['/'] }], 'dot-notation': 'error', 'no-useless-return': 'error', 'prefer-arrow-callback': ['error', { allowNamedFunctions: true, allowUnboundThis: true }], 'prefer-destructuring': [ 'error', { VariableDeclarator: { array: false, object: true }, AssignmentExpression: { array: false, object: false } } ], yoda: ['error', 'never', { exceptRange: true }] }; /** * ⚠️ !!!STOP: ESSENTIAL RULES MUST BE AUTOFIXABLE !!! ⚠️ * If adding a typescript-eslint version of an existing ESLint rule, * make sure to disable the ESLint rule here. * * Also, please make sure rule doesn't require type information * as type information is not generated because it can be time consuming. */ const essentialTypescriptRules = { '@typescript-eslint/no-inferrable-types': 'error', '@typescript-eslint/prefer-function-type': 'error', '@typescript-eslint/array-type': ['error', { default: 'array-simple' }] }; /** * When adding rules here, you need to make sure they are compatible with * `typescript-eslint`, as some rules such as `no-array-constructor` aren't compatible. */ const strictRules = { 'no-compare-neg-zero': 'error', 'no-cond-assign': 'error', 'no-console': [ 'error', { allow: [ 'warn', 'error', 'info', 'time', 'timeEnd', 'timeLog', 'debug', 'clear', 'group', 'groupCollapsed', 'groupEnd' ] } ], 'no-constant-condition': ['error', { checkLoops: false }], 'no-debugger': 'error', 'no-duplicate-case': 'error', 'no-empty': ['error', { allowEmptyCatch: true }], 'no-empty-character-class': 'error', 'no-extra-boolean-cast': 'error', 'no-invalid-regexp': 'error', 'no-sparse-arrays': 'error', 'no-unsafe-finally': 'error', 'no-unsafe-negation': 'error', 'require-atomic-updates': 'error', 'use-isnan': 'error', eqeqeq: ['error', 'always', { null: 'ignore' }], 'guard-for-in': 'error', 'no-caller': 'error', 'no-empty-pattern': 'error', 'no-eval': 'error', 'no-extend-native': 'error', 'no-extra-bind': 'error', 'no-implied-eval': 'error', // 'no-invalid-this': 'error', // not working on class properties: https://github.com/typescript-eslint/typescript-eslint/issues/491 // 'no-new': 'error', // disabled because AWS-CDK is breaking this rule extensively 'no-new-wrappers': 'error', 'no-return-await': 'error', 'no-script-url': 'error', 'no-self-assign': 'error', 'no-useless-catch': 'error', 'no-useless-escape': 'error', radix: ['error', 'as-needed'], 'no-delete-var': 'error', 'no-buffer-constructor': 'error', 'prefer-const': 'error', 'prefer-numeric-literals': 'error', 'prefer-rest-params': 'error', 'prefer-spread': 'error', 'require-yield': 'error', 'symbol-description': 'error', 'import/no-deprecated': 'warn' // Disabled as it raises false-positive error in components like this: // // <Dictionary> // {[ // ['Source', data.articleOne.sources.join(', ')], // ['Published', <LocaleDate date={data.articleOne.appearedAt} />], // ]} // </Dictionary> // // 'react/jsx-key': ['error', { checkFragmentShorthand: true }] // Enable the following JSX rules to fix false-positive errors when no-unused-vars rule is used! // 'react/jsx-uses-vars': 'error', // 'react/jsx-uses-react': 'error' }; /** * If adding a typescript-eslint version of an existing ESLint rule, * make sure to disable the ESLint rule here. * * Also, please make sure rule doesn't require type information * as type information is not generated because it can be time consuming. */ const strictTypescriptRules = { '@typescript-eslint/prefer-for-of': 'error', '@typescript-eslint/adjacent-overload-signatures': 'error', '@typescript-eslint/no-empty-interface': 'error', '@typescript-eslint/no-require-imports': 'error', '@typescript-eslint/no-useless-constructor': 'error', '@typescript-eslint/no-this-alias': ['error', { allowDestructuring: true }] }; export const preCommitLintConfig = toLintConfig({ rules: essentialRules, tsOnlyRules: essentialTypescriptRules, plugins: ['react'] }); export const checkupLintConfig = toLintConfig({ rules: { ...essentialRules, ...strictRules }, tsOnlyRules: { ...essentialTypescriptRules, ...strictTypescriptRules }, plugins: ['react', 'import'] }); // export const editorLintConfig = toLintConfig({ // rules: strictRules, // tsOnlyRules: strictTypescriptRules, // plugins: ['react', 'import'] // }); function toLintConfig({ rules, tsOnlyRules, plugins }: { rules: object; tsOnlyRules: object; plugins: string[]; }) { return { root: true, env: { browser: true, commonjs: true, es6: true, jest: true, node: true }, settings: { react: { version: '999.999.999' } }, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { jsx: true } }, plugins, overrides: [ { files: ['*.ts?(x)'], plugins: ['@typescript-eslint'], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { jsx: true }, warnOnUnsupportedTypeScriptVersion: true }, rules: tsOnlyRules } ], rules }; } <file_sep>/src/cpu.ts import os from 'os'; let currentlyRunning = 0; const queue: Array<() => void> = []; /** * "Allocates" one CPU core. */ export async function allocateCore(): Promise<{ free: () => void }> { const free = () => { currentlyRunning--; const startNext = queue.shift(); if (startNext) startNext(); }; if (currentlyRunning < os.cpus().length) { currentlyRunning++; return Promise.resolve({ free }); } return new Promise(resolve => { queue.push(() => { currentlyRunning++; resolve({ free }); }); }); } <file_sep>/src/store.ts import Configstore from 'configstore'; import { Context } from './context'; const incompleteChecksTTL = 60 * 60 * 1000; const incompleteChecksKey = 'incompleteChecks'; const store = new Configstore('@deftomat/opinionated', { [incompleteChecksKey]: [] }); export function updateIncompleteChecks({ projectRoot }: Context, checks: Iterable<string>) { const now = Date.now(); const entries: IncompleteChecksEntry[] = store.get(incompleteChecksKey); const index = entries.findIndex(entryFor(projectRoot, now)); const entry: IncompleteChecksEntry = { key: projectRoot, at: now, checks: Array.from(checks) }; if (index === -1) { entries.push(entry); } else { entries[index] = entry; } const valid = entries.filter(({ at }) => now <= at + incompleteChecksTTL); store.set(incompleteChecksKey, valid); } export function getIncompleteChecks({ projectRoot }: Context): Set<string> { const now = Date.now(); const incomplete = store.get(incompleteChecksKey); const entry: IncompleteChecksEntry | undefined = incomplete.find(entryFor(projectRoot, now)); if (entry) return new Set(entry.checks); return new Set(); } interface IncompleteChecksEntry { readonly key: string; readonly at: number; readonly checks: string[]; } function entryFor(projectRoot: string, now: number) { return ({ key, at }) => key === projectRoot && now <= at + incompleteChecksTTL; } <file_sep>/configs/tsconfig.json { "compileOnSave": false, "compilerOptions": { "allowSyntheticDefaultImports": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": false, "pretty": true, "strict": true, "useUnknownInCatchVariables": false, "noImplicitOverride": true, "strictPropertyInitialization": false } }
dc5a3873cf539d5bb9adba711244bedc5415d8c1
[ "Markdown", "TypeScript", "JSON with Comments", "JavaScript" ]
24
TypeScript
deftomat/opinionated
3684c67c5f4a565ce13c3f2b6484273c6abaae40
35a07cef9d918adc5aa74a2fbfea7a6cdc2ec0b4
refs/heads/master
<repo_name>angobey85/andesiot_app<file_sep>/api/models/data.js import mongoose from "mongoose"; const Schema = mongoose.Schema; const dataSchema = new Schema({ data_userId: { type: String, required: [true] }, data_equipment_id: { type: String, required: [true] }, data_variable: { type: String, required: [true] }, data_value: { type: Number, required: [true] }, data_time: { type: Number, required: [true] } }); // Convertir a modelo const Data = mongoose.model("Data", dataSchema); export default Data;<file_sep>/api/models/emqx_alarm_rule.js import mongoose from 'mongoose'; const Schema = mongoose.Schema; const alarmRuleSchema = new Schema({ alarmrule_user_id: {type: String, required: [true]}, alarmrule_equipment_id: { type: String, required: [true] }, alarmrule_emqx_rule_id: { type: String, required: [true] }, alarmrule_variable_name: { type: String }, alarmrule_variable_id: { type: String }, alarmrule_value: {type: Number}, alarmrule_condition: { type: String }, alarmrule_triggerTime: { type: Number }, alarmrule_status: { type: Boolean }, alarmrule_counter: { type: Number, default: 0}, alarmrule_createdTime: {type: Number} }); const AlarmRule = mongoose.model('alarmRule', alarmRuleSchema); export default AlarmRule; <file_sep>/api/index.js //REQUERIMIENTOS const express = require("express"); const mongoose = require("mongoose"); const morgan = require("morgan"); const cors = require("cors"); const colors = require("colors"); require('dotenv').config(); //INTANCIAS const app = express(); //EXPRESS CONFIG app.use(morgan("tiny")); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cors()); //RUTAS EXPRESS app.use('/api', require('./routes/devices.js')); app.use('/api', require('./routes/users.js')); app.use('/api', require('./routes/variables.js')); app.use('/api', require('./routes/templates.js')); app.use('/api', require('./routes/equipments.js')); app.use('/api', require('./routes/webhooks.js')); app.use('/api', require('./routes/emqxapis.js')); app.use('/api', require('./routes/alarms.js')); app.use('/api', require('./routes/dataprovide.js')); module.exports = app; //LISTENER app.listen(process.env.API_PORT, () =>{ console.log("API Servidor escuchando en el puerto " + process.env.API_PORT); }); if (process.env.environment != "dev") { const app2 = express(); app2.listen(3002, function(){ console.log("LISTENING ON PORT 3002"); }); app2.all('*', function(req,res){ console.log("NO SSL ACCESS REDIRECTING"); return res.redirect("https://" + req.headers["host"] + req.url); }); } //MONGO CONEXION const mongoUserName = process.env.MONGO_USERNAME; const mongoPassword = <PASSWORD>; const mongoHost = process.env.MONGO_HOST; const mongoPort = process.env.MONGO_PORT; const mongoDatabase = process.env.MONGO_DATABASE; var uri = "mongodb://" + mongoUserName + ":" + mongoPassword + "@" + mongoHost + ":" + mongoPort + "/" + mongoDatabase; const options = { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useNewUrlParser: true, authSource: "admin" }; mongoose.connect(uri, options).then(()=>{ console.log("\n"); console.log("*************************************".green); console.log("SE HA CONECTADO A MONGO CORRECTAMENTE".green); console.log("*************************************".green); console.log("\n"); global.check_mqtt_superuser(); }, (err)=>{ console.log("\n"); console.log("******************************".red); console.log("HA FALLADO LA CONEXION A MONGO".red); console.log("******************************".red); console.log("\n"); } ); <file_sep>/api/models/emqx_saver_rule.js import mongoose from "mongoose"; const uniqueValidator = require("mongoose-unique-validator"); const Schema = mongoose.Schema; const saveRuleSchema = new Schema({ saverule_user_id: { type: String, required: [true] }, saverule_equipment_id: { type: String, required: [true]}, saverule_emqx_rule_id: { type: String, required: [true]}, saverule_status: { type: Boolean, required: [true]} }); //Validator saveRuleSchema.plugin(uniqueValidator, { message: 'Error, Regla ya Existe.'}); // convert to model const SaveRule = mongoose.model('SaveRule', saveRuleSchema); export default SaveRule; <file_sep>/api/models/emqx_auth.js import mongoose from "mongoose"; const uniqueValidator = require("mongoose-unique-validator"); const Schema = mongoose.Schema; const emqxRuleSchema = new Schema({ user_id: { type: String, required: [true] }, equipment_id: { type: String }, username: { type: String, required: [true]}, password: { type: String, required: [true]}, publish: { type: Array}, subscribe: { type: Array}, type: { type: String, required: [true]}, date: { type: Number}, updateDate: { type: Number} }); //Validator // convert to model const EmqxRule = mongoose.model('EmqxRule', emqxRuleSchema); export default EmqxRule;<file_sep>/api/routes/emqxapis.js const express = require("express"); const router = express.Router(); const axios = require('axios'); const colors = require('colors'); import EmqxRule from "../models/emqx_auth.js"; const auth = { auth: { username: 'admin', password: <PASSWORD>.env.EMQX_APPLICATION_SECRET } } global.saverResource = null; global.alarmResource = null; // EMQX async function listResources(){ const url = "http://" +process.env.EMQX_NODE_HOST+ ":8085/api/v4/resources/" const res = await axios.get(url, auth); const size = res.data.data.length; try { if (res.status ===200) { if (size == 0) { console.log("Creando Emqx webhook".green) createResources(); }else if(size == 2) { res.data.data.forEach(resource=> { if (resource.description == "alarm-webhook") { global.alarmResource = resource; } if (resource.description == "saver-webhook") { global.saverResource = resource; } }); }else{ function printWarning(){ console.log("BORRE TODO LOS WEBHOOK EMQX Y RESETE EL NODE"); setTimeout(() => { printWarning(); }, 1000); } printWarning(); } }else{ console.log("ERROR AL CONSULTAR API EMQX") } } catch (error) { console.log("Error al listar los recursos EMQX"); console.log(error); } } async function createResources(){ const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/resources"; const data1 = { "type": "web_hook", "config": { url: "http://"+process.env.EMQX_NODE_HOST+":3001/api/saver-webhook", headers: { token: process.env.EMQX_API_TOKEN }, method: "POST" }, description: "saver-webhook" } const data2 = { "type": "web_hook", "config": { url: "http://"+process.env.EMQX_NODE_HOST+":3001/api/alarm-webhook", headers: { token: process.env.EMQX_API_TOKEN }, method: "POST" }, description: "alarm-webhook" } const res1 = await axios.post(url, data1, auth); if (res1.status ===200) { console.log("Recursos de Guardado Creado") } const res2 = await axios.post(url, data2, auth); if (res2.status ===200) { console.log("Recursos de Alarma Creado") } setTimeout(() => { console.log("Eqmx Web Hooks Creados") listResources(); }, 1000); } //check if superuser exist if not we create one global.check_mqtt_superuser = async function checkMqttSuperUser(){ try { const superusers = await EmqxRule.find({type:"superuser"}); if (superusers.length > 0 ) { return; }else if ( superusers.length == 0 ) { await EmqxRule.create( { publish: ["#"], subscribe: ["#"], user_id: "aaaaaaaaaaa", username: "superuser", password: "<PASSWORD>", type: "superuser", date: Date.now(), updatedDate: Date.now() } ); console.log("Mqtt super user created") } } catch (error) { console.log("error creating mqtt superuser "); console.log(error); } } setTimeout(() => { listResources(); }, process.env.EMQX_DELAY); module.exports = router;<file_sep>/api/models/user.js import mongoose from "mongoose"; const uniqueValidator = require("mongoose-unique-validator"); const Schema = mongoose.Schema; const userSchema = new Schema({ user_name: { type: String, required: [true] }, user_email: { type: String, required: [true], unique: true}, user_password: { type: String, required: [true]}, }); //Validator userSchema.plugin(uniqueValidator, { message: 'Error, Email ya Existe.'}); // convert to model const User = mongoose.model('User', userSchema); export default User; <file_sep>/api/models/equipment.js import mongoose from "mongoose"; const uniqueValidator = require("mongoose-unique-validator"); const Schema = mongoose.Schema; const equipmentSchema = new Schema({ equipment_user_id: { type: String, required: [true] }, equipment_id: { type: String, required: [true], unique: true }, equipment_name: { type: String, required: [true]}, equipment_brand: { type: String, required: [true]}, equipment_model: { type: String, required: [true]}, equipment_tag: { type: String, required: [true]}, equipment_template_name: { type: String, required: [true]}, equipment_template_id: { type: String, required: [true]}, equipment_selected: { type: Boolean, required: [true], default: false }, equipment_date: { type: Number} }); //Validator equipmentSchema.plugin(uniqueValidator, { message: 'Error, Equipment ya Existe.'}); // convert to model const Equipment = mongoose.model('Equipment', equipmentSchema); export default Equipment; <file_sep>/api/routes/users.js const express = require("express"); const router = express.Router(); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); const {checkAuth} = require('../middlewares/authentication.js'); //models import import User from "../models/user.js"; import EmqxRule from "../models/emqx_auth.js" //AUTH router.post("/register", async (req, res) => { try { const encrypterPassword = bcrypt.hashSync(req.body.user_password, 10); const newUser = { user_name: req.body.user_name, user_email: req.body.user_email, user_password: <PASSWORD> } const user = await User.create(newUser); const toSend = { status: "success", } res.json(toSend); } catch (error) { console.log ("ERROR - INSERTAR ENDPOINT") console.log (error); const toSend = { status: "error", error: error } res.status(500).json(toSend); } }); router.post("/login", async(req, res) => { const email = req.body.user_email; const password = <PASSWORD>; var user = await User.findOne({ user_email: email }); if(!user){ const toSend = { status: "error", error: "Credenciales Invalidas" } return res.status(401).json(toSend); } if (bcrypt.compareSync(password, user.user_password)){ user.set('user_password', undefined, {strict: false}); //eliminar pass de user const token = jwt.sign({userData: user}, 'securePasswordHere', {expiresIn: 60*60*24*30 }); const toSend = { status: "success", token: token, userData: user } return res.status(200).json(toSend); }else{ const toSend = { status: "error", error: "Credenciales Invalidas" } return res.status(401).json(toSend); } console.log(user); res.json({"status":"success"}); }); router.get("/new-user", async (req, res) => { try { const user = await User.create({ user_name: "<NAME>", user_email: "<EMAIL>", user_password: "<PASSWORD>" }); res.json({"status":"success"}) } catch (error) { console.log(error); res.json({"status":"fail"}); } }); //MQTT CREDENCIALES WEB router.post("/getMqttCredentials", checkAuth, async (req, res) =>{ try { const userId = req.userData._id; const credentials = await getWebUserMqtt(userId); const toSend = { status: "success", username: credentials.username, password: <PASSWORD> } res.json(toSend); setTimeout(() => { getWebUserMqtt(userId) }, 10000); return } catch (error) { console.log(error); const toSend = { status: "error", }; return res.status(500).json(toSend); } }); router.post("/getMqttReconnection", checkAuth, async (req, res) =>{ const userId = req.userData._id; const credentials = await getWebUserMqttReconnection(userId); const toSend = { status: "success", username: credentials.username, password: <PASSWORD> } console.log(toSend) res.json(toSend); setTimeout(() => { getWebUserMqtt(userId) }, 15000); }) //MQTT TIPOS DE CREDENCIALES async function getWebUserMqtt(userId){ try { var rule = await EmqxRule.find({type: "user", user_id: userId}); if (rule.length == 0) { const newRule = { user_id: userId, username: makeid(10), password: makeid(10), publish: ["+/" + userId + "/#"], subscribe: ["+/" + userId + "/#"], type: "user", date: Date.now(), updateDate: Date.now() } const result = await EmqxRule.create(newRule); const toSend = { username: result.username, password: <PASSWORD> } return toSend; } const newUserName = makeid(10); const newPassword = <PASSWORD>(10); const result = await EmqxRule.updateOne({type:"user", user_id: userId}, {$set:{username: newUserName, password: <PASSWORD>, updateDate: Date.now()}}) if (result.n == 1 && result.ok ==1) { return { username: newUserName, password: <PASSWORD> } }else{ return false; } } catch (error) { console.log(error); return false; } } async function getWebUserMqttReconnection(userId){ try { const rule = await EmqxRule.find({type:"user", user_id: userId }); if (rule.length == 1) { const toSend = { username: rule[0].username, password: rule[0].password } return toSend; } } catch (error) { console.log(error); return false; } } function makeid(length) { var result = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt( Math.floor(Math.random() * charactersLength) ); } return result; } module.exports = router; <file_sep>/api/routes/variables.js //REQUERIMIENTOS const express = require("express"); const router = express.Router(); const {checkAuth} = require('../middlewares/authentication.js'); const { default: Variable } = require("../models/variable.js"); /* __ __ ___ _ ____ _____ _ ___ ____ | \/ |/ _ \| | | _ \| ____| | / _ \/ ___| | |\/| | | | | | | | | | _| | | | | | \___ \ | | | | |_| | |___| |_| | |___| |__| |_| |___) | |_| |_|\___/|_____|____/|_____|_____\___/|____/ */ import variable from '../models/variable.js'; /* _ ____ ___ / \ | _ |_ _| / _ \ | |_) | | / ___ \| __/| | /_/ \_|_| |___| */ //CONSULTAR router.get("/variable", checkAuth, async (req, res) => { try { const userId = req.userData._id; const variables = await Variable.find({variable_user_id: userId}); const toSend = { status: "success", data: variables } res.json(toSend); } catch (error) { const toSend = { status: "error", data: error } console.log ("ERROR AL CONSULTAR VARIABLES") res.json(toSend); } }); //INSERTAR router.post("/variable", checkAuth, async (req, res) => { try { const userId = req.userData._id; var newVariable = req.body.newVariable; console.log(newVariable); newVariable.variable_user_id = req.userData._id; newVariable.variable_date = Date.now(); const variable = await Variable.create(newVariable); const toSend = { status: "success", } return res.json(toSend); } catch (error) { console.log("ERROR CREANDO LA VARIABLE"); console.log(error); const toSend = { status: "Error", error: error } return res.status(500).json(toSend); } }); // BORRAR router.delete("/variable",checkAuth, async (req, res) => { try { const userId = req.userData._id; const variableId = req.query.variable_id const result = await Variable.deleteOne({variable_user_id: userId, variable_id: variableId}) const toSend = { status: "success", data: result }; return res.json(toSend); } catch (error) { console.log("ERROR AL BORRAR LA VARIABLE"); console.log(error); const toSend = { status: "Error", error: error } return res.status(500).json(toSend); } }); // ACTUALIZAR router.put("/device", (req, res) => { }); /* */ module.exports = router;<file_sep>/api/models/notification.js import mongoose from 'mongoose'; const Schema = mongoose.Schema; const notificationSchema = new Schema({ notification_user_id: { type: String, required: [true] }, notification_equipment_name: { type: String, required: [true] }, notification_equipment_id: { type: String, required: [true] }, notification_payload: { type: Object }, notification_emqx_rule_id: { type: String, required: [true] }, notification_topic: { type: String, required: [true] }, notification_value: { type: Number, required: [true] }, notification_condition: { type: String, required: [true] }, notification_variable_name: { type: String, required: [true] }, notification_variable_id: { type: String, required: [true] }, notification_readed: {type: Boolean, required: [true]}, notification_date: {type: Number, required: [true]} }); const Notification = mongoose.model('Notification', notificationSchema); export default Notification; <file_sep>/api/routes/templates.js //REQUERIMIENTOS const express = require("express"); const router = express.Router(); const {checkAuth} = require('../middlewares/authentication.js'); const { default: Template } = require("../models/template.js"); import template from '../models/template.js'; //CONSULTAR router.get("/template", checkAuth, async (req, res) => { try { const userId = req.userData._id; const templates = await Template.find({template_user_id: userId}); const toSend = { status: "success", data: templates } res.json(toSend); } catch (error) { const toSend = { status: "error", data: error } console.log ("ERROR AL CONSULTAR DISPOSITIVOS") res.json(toSend); } }); //INSERTAR router.post("/template", checkAuth, async (req, res) => { try { const userId = req.userData._id; var newTemplate = req.body.template; console.log(newTemplate); newTemplate.template_user_id = userId; newTemplate.template_date = Date.now(); const template = await Template.create(newTemplate); const toSend = { status: "success", } return res.json(toSend); } catch (error) { console.log("ERROR CREANDO LA PLANTILLA"); console.log(error); const toSend = { status: "Error", error: error } return res.status(500).json(toSend); } }); // BORRAR router.delete("/template",checkAuth, async (req, res) => { try { const userId = req.userData._id; const templateId = req.query.template_id const result = await Template.deleteOne({template_user_id: userId, _id: templateId}) const toSend = { status: "success", data: result }; return res.json(toSend); } catch (error) { console.log("ERROR BORRANDO LA PLANTILLA"); console.log(error); const toSend = { status: "error", error: error } return res.status(500).json(toSend); } }); module.exports = router;<file_sep>/api/routes/equipments.js //REQUERIMIENTOS const express = require("express"); const router = express.Router(); const {checkAuth} = require('../middlewares/authentication.js'); const { default: Equipment } = require("../models/equipment.js"); const axios = require('axios'); /* __ __ ___ _ ____ _____ _ ___ ____ | \/ |/ _ \| | | _ \| ____| | / _ \/ ___| | |\/| | | | | | | | | | _| | | | | | \___ \ | | | | |_| | |___| |_| | |___| |__| |_| |___) | |_| |_|\___/|_____|____/|_____|_____\___/|____/ */ import equipment from '../models/equipment.js'; import SaveRule from '../models/emqx_saver_rule.js'; import Template from '../models/template.js'; import AlarmRule from '../models/emqx_alarm_rule.js'; /* _ ____ ___ / \ | _ |_ _| / _ \ | |_) | | / ___ \| __/| | /_/ \_|_| |___| */ const auth = { auth: { username: 'admin', password: <PASSWORD>APPLICATION_<PASSWORD> } } //CONSULTAR router.get("/equipment", checkAuth, async (req, res) => { try { const userId = req.userData._id; //OBTENER EQUIPOS var equipments = await Equipment.find({equipment_user_id: userId}); //ARRAY MONGOOSE A ARRAY JS equipments = JSON.parse(JSON.stringify(equipments)); //OBTENER REGLA DE SAVER const saveRules = await getSaveRules(userId) //OBTENER ALARMAS const alarmRules = await getAlarmRules(userId) //OBTENER PLANTILLAS const templates = await getTemplates(userId) //REGLA SAVER A EQUIPOS equipments.forEach((equipment, index) => { equipments[index].equipment_saveRule = saveRules.filter(saveRule => saveRule.saverule_equipment_id == equipment.equipment_id)[0]; equipments[index].template = templates.filter(template => template._id == equipment.equipment_template_id)[0]; equipments[index].alarmRule = alarmRules.filter(alarmRule => alarmRule.alarmrule_equipment_id == equipment.equipment_id); }); const toSend = { status: "success", data: equipments } res.json(toSend); } catch (error) { const toSend = { status: "error", data: error } console.log ("ERROR AL CONSULTAR EQUIPOS") res.json(toSend); } }); //INSERTAR router.post("/equipment", checkAuth, async (req, res) => { try { const userId = req.userData._id; var newEquipment = req.body.newEquipment; newEquipment.equipment_user_id = req.userData._id; newEquipment.equipment_date = Date.now(); await createSaveRule(userId, newEquipment.equipment_id, true); const equipment = await Equipment.create(newEquipment); const toSend = { status: "success", } return res.json(toSend); } catch (error) { console.log("ERROR AL CREAR EL EQUIPO"); console.log(error); const toSend = { status: "error", error: error } return res.status(500).json(toSend); } }); // BORRAR router.delete("/equipment",checkAuth, async (req, res) => { try { const userId = req.userData._id; const equipmentId = req.query.equipment_id await deleteSaveRule(equipmentId); const result = await Equipment.deleteOne({equipment_user_id: userId, equipment_id: equipmentId}) const toSend = { status: "success", data: result }; return res.json(toSend); } catch (error) { console.log("ERROR AL BORRAR EL EQUIPO"); console.log(error); const toSend = { status: "Error", error: error } return res.status(500).json(toSend); } }); // ACTUALIZAR router.put("/equipment",checkAuth, async (req, res) => { const eId = req.body.equipment_id; const userId = req.userData._id; if (await selectEquipment(userId, eId)) { const toSend = { status: "success" }; return res.json(toSend); } else { const toSend = { status: "error" }; return res.json(toSend); } }); // ACTUALIZAR REGLA SAVER router.put("/saver-rule",checkAuth, async (req, res) => { const rule = req.body.rule; await updateSaveRuleStatus(rule.saverule_emqx_rule_id, rule.saverule_status) const toSend = { status: "success" }; res.json(toSend); }); /* _____ _ _ _ _ ____ ___ ___ _ _ _____ ____ | ___| | | | \ | |/ ___|_ _/ _ \| \ | | ____/ ___| | |_ | | | | \| | | | | | | | \| | _| \___ \ | _| | |_| | |\ | |___ | | |_| | |\ | |___ ___) | |_| \___/|_| \_|\____|___\___/|_| \_|_____|____/ */ async function selectEquipment(userId, eId) { try { const result = await Equipment.updateMany( { equipment_user_id: userId }, { equipment_selected: false } ); const result2 = await Equipment.updateOne( { equipment_id: eId, equipment_user_id: userId }, { equipment_selected: true } ); return true; } catch (error) { console.log("ERROR IN 'selectEquipment' FUNCTION "); console.log(error); return false; } } //OBTENER PLANTILLA async function getTemplates(userId) { try { const templates = await Template.find({ template_user_id: userId }); return templates; } catch (error) { return false; } } //OBTENER REGLA SAVER async function getSaveRules(userId) { try { const rules = await SaveRule.find({ saverule_user_id: userId }); return rules; } catch (error) { return false; } } //OBTENER REGLA SAVER async function getAlarmRules(userId) { try { const rules = await AlarmRule.find({ alarmrule_user_id: userId }); return rules; } catch (error) { return false; } } //CREAR REGLA SAVER async function createSaveRule(userId, equipment_id, status){ try { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules" const topic = "data/" + userId + "/" + equipment_id + "/+"; const rawsql = 'SELECT topic, payload FROM \"' + topic + '\" WHERE payload.save=1'; var newRule = { rawsql : rawsql, actions: [ { name: "data_to_webserver", params: { $resource: global.saverResource.id, payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}' } } ], description: "SAVER-RULE", enabled: status }; const res = await axios.post(url,newRule, auth); if (res.status === 200 && res.data.data) { console.log(res.data.data); await SaveRule.create({ saverule_user_id: userId, saverule_equipment_id: equipment_id, saverule_emqx_rule_id: res.data.data.id, saverule_status: status }); return true; }else{ return false; } } catch (error) { console.log("Error al crear la regla Saver") console.log(error) } } //ACTUALIZAR REGLA SAVER async function updateSaveRuleStatus(emqxRuleId, status) { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId; const newRule = { enabled: status }; const res = await axios.put(url, newRule, auth); if (res.status === 200 && res.data.data) { await SaveRule.updateOne({ saverule_emqx_rule_id: emqxRuleId }, { saverule_status: status }); console.log("Saver Rule Status Updated...".green); return { status: "success", action: "updated" }; } } //BORRAR REGLA SAVER async function deleteSaveRule(dId) { try { const mongoRule = await SaveRule.findOne({ saverule_equipment_id: dId }); const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.saverule_emqx_rule_id; const emqxRule = await axios.delete(url, auth); const deleted = await SaveRule.deleteOne({ saverule_equipment_id: dId }); return true; } catch (error) { console.log("Error deleting saver rule"); console.log(error); return false; } } module.exports = router;<file_sep>/api/models/device.js import mongoose from "mongoose"; const uniqueValidator = require("mongoose-unique-validator"); const Schema = mongoose.Schema; const deviceSchema = new Schema({ device_user_id: { type: String, required: [true] }, device_id: { type: String, required: [true], unique: true}, device_serie: { type: String, required: [true]}, device_name: { type: String, required: [true]}, device_model: { type: String, required: [true]}, device_date: { type: Number} }); //Validator deviceSchema.plugin(uniqueValidator, { message: 'Error, Dispositivo ya Existe.'}); // convert to model const Device = mongoose.model('Device', deviceSchema); export default Device;
eca406111485faff452a823274358877f3209244
[ "JavaScript" ]
14
JavaScript
angobey85/andesiot_app
91b4ef76064fc2f18896405abf382bc8e41aa56f
b905b13f9af6f8dd7c4e0bdc85f4ed060a4fdedb
refs/heads/develop
<file_sep># NoteMaker This a note making and sending app build using express , mongodb and nodejs , allowing an user to create and send notes to a particular person on his/her email id. Pre Requisites : 1. Make sure that you have mongodb Installed on your system and congfigured it properly by setting up the command line environment path. You can download it from https://www.mongodb.com/download-center/community . 2. Allow / Enable less secure apps access to your gmail account by going through your gmail account settings. You can do it directly from https://myaccount.google.com/lesssecureapps . Steps To Run : 1. Clone the repository on your system . 2. Edit users.js file in routes folder to set up your gmail smtp settings by providing your gmail id and gmail account password . 3. Open a command prompt and run mongodb by typing mongod. 4. Run the server by using the command npm start. 5. In your browser , run the app on port 5000 by typing http://localhost:5000 as URL. <file_sep>const mongoose = require('mongoose'); const Schema = mongoose.Schema; const user= require('./user'); const messagecontentsSchema = new Schema({ username : String, to: String, html:String }); const MessageContents = mongoose.model('messagecontents', messagecontentsSchema); module.exports = MessageContents;<file_sep>const express = require('express'); const router = express.Router(); const Joi = require('joi'); const passport = require('passport'); const randomstring = require('randomstring'); const nodemailer = require('nodemailer'); const messagecontents = require('../models/messagecontents'); var mongo = require('mongodb'); var assert = require('assert'); const verificationtransport = nodemailer.createTransport({ service: 'gmail', port: 465, secure: true, auth: { user: '<EMAIL>', pass: '<PASSWORD>' }, tls: { rejectUnauthorized: false } }); const notetransport = nodemailer.createTransport({ service: 'gmail', port: 465, secure: true, auth: { user: '<EMAIL>', pass: '<PASSWORD>' }, tls: { rejectUnauthorized: false } }); const User = require('../models/user'); // Validation Schema const userSchema = Joi.object().keys({ email: Joi.string().email().required(), username: Joi.string().required(), password: Joi.string().regex(/^[a-<PASSWORD>]{3,30}$/).required(), confirmationPassword: Joi.any().valid(Joi.ref('password')).required() }); // Authorization const isAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { return next(); } else { req.flash('error', 'Sorry, but you must be registered/logged in first!!!!!'); res.redirect('/'); } }; const isNotAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { req.flash('error', 'Sorry, but you are already logged in!!!!!'); res.redirect('/'); } else { return next(); } }; router.route('/register') .get(isNotAuthenticated, (req, res) => { res.render('register'); }) .post(async (req, res, next) => { try { const result = Joi.validate(req.body, userSchema); if (result.error) { req.flash('error', 'Data is not valid. Please try again.'); res.redirect('/users/register'); return; } // Checking if email is already taken const user = await User.findOne({ 'email': result.value.email }); if (user) { req.flash('error', 'Email is already in use.'); res.redirect('/users/register'); return; } // Hash the password const hash = await User.hashPassword(result.value.password); // Generate secret token const secretToken = randomstring.generate(); console.log('secretToken', secretToken); // Save secret token to the DB result.value.secretToken = secretToken; // Flag account as inactive result.value.active = false; // Save user to DB delete result.value.confirmationPassword; result.value.password = <PASSWORD>; const newUser = await new User(result.value); console.log('newUser', newUser); await newUser.save(function(err, savedUser){ if(err){ console.log(err); return res.status(500).send(); } console.log("User Created!") }); // Compose email const html = `Hi there, <br/> Thank you for registering! <br/><br/> Please verify your email by typing the following token(In case you copy it , make sure that you remove the extra space added to the text before submitting): <br/> Token: <b>${secretToken}</b> <br/> On the following page: <a href="http://localhost:5000/users/verify">Click Here To Verify</a> <br/><br/> Have a pleasant day. <br/><br/> &copy; 2019 Note Maker (By <NAME>)` const from = '<EMAIL>'; let mailOptions = { from :from, to : result.value.email, subject : 'Please Verify Your Acoount', html : html }; // Send email await verificationtransport.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.messageId); }); req.flash('success', 'Please check your email!!!!!'); res.redirect('/users/login'); } catch(error) { next(error); } }); router.route('/login') .get(isNotAuthenticated, (req, res) => { res.render('login'); }) .post(passport.authenticate('local', { successRedirect: '/users/dashboard', failureRedirect: '/users/login', failureFlash: true })); router.route('/dashboard') .get(isAuthenticated, (req, res) => { res.render('dashboard', { username: req.user.username }); }); router.route('/verify') .get(isNotAuthenticated, (req, res) => { res.render('verify'); }) .post(async (req, res, next) => { try { const { secretToken } = req.body; // Find account with matching secret token const user = await User.findOne({ 'secretToken': secretToken }); if (!user) { req.flash('error', 'No user found!!!!!'); res.redirect('/users/verify'); return; } user.active = true; user.secretToken = ''; await user.save(); req.flash('success', 'Thank you! Now you may login.'); res.redirect('/users/login'); } catch(error) { next(error); } }) router.route('/logout') .get(isAuthenticated, (req, res) => { req.logout(); req.flash('success', 'Successfully logged out. Hope to see you soon!!!!!'); res.redirect('/'); }); router.route('/makenote') .get(isAuthenticated, (req, res) => { res.render('makenote', { username: req.user.username }); }); router.route('/newnote') .get(isAuthenticated, (req, res) => { res.render('newnote'); }); router.post('/newnote' ,async function(req,res,next){ const text =`<br/><br/> Sent via Note Maker (By <NAME>) <br/> Come Join Us At : <a href="http://localhost:5000">Click Here To Join Us</a> <br/> Have a pleasant day. <br/><br/> &copy; 2019 Note Maker (By <NAME>)` const from = '<EMAIL>'; let mailOptions = { from :from, to : req.body.email, subject : req.user.username + ' Via Note Maker (By <NAME>) ', html : req.body.message + text }; // Send email await notetransport.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.messageId); }); var notebody = { username: req.user.username, to : req.body.to, html : req.body.message }; mongo.connect('mongodb://localhost:27017/messagecontents',function(err,db){ assert.equal(null,err); db.collection('messagecontents').insertOne(notebody , function (err,result){ assert.equal(null,err); console.log('notemade'); db.close(); } ) }) req.flash('success', 'Note Sent!!!!!'); res.redirect('/users/dashboard'); }); router.route('/getnotes') .get(isAuthenticated, (req, res , next) => { var notesarray =[]; mongo.connect('mongodb://localhost:27017/messagecontents', function(err,db){ assert.equal(null,err); var cursor = db.collection('messagecontents').find({username : req.user.username }); cursor.forEach(function(doc,err){ assert.equal(null,err); notesarray.push(doc); }, function () { db.close(); console.log(notesarray); res.render('getnotes', {data : notesarray}); }); }); }); module.exports = router;
f2f0acff6101268a3e9e918002f0d24533cb1bd4
[ "Markdown", "JavaScript" ]
3
Markdown
mjindal585/NoteMaker
290b90d12d6d93aaa4fb4a2946d9b1dc9ee05f54
e285d0b444f2a0e153221746637cdc4c07673a8f
refs/heads/master
<repo_name>vlakoff/framework<file_sep>/src/Illuminate/Database/Schema/ColumnDefinition.php <?php namespace Illuminate\Database\Schema; use Illuminate\Database\Query\Expression; use Illuminate\Support\Fluent; /** * @method static after(string $column) Place the column "after" another column (MySQL) * @method static always() Used as a modifier for generatedAs() (PostgreSQL) * @method static autoIncrement() Set INTEGER columns as auto-increment (primary key) * @method static change() Change the column * @method static charset(string $charset) Specify a character set for the column (MySQL) * @method static collation(string $collation) Specify a collation for the column (MySQL/PostgreSQL/SQL Server) * @method static comment(string $comment) Add a comment to the column (MySQL) * @method static default(mixed $value) Specify a "default" value for the column * @method static first() Place the column "first" in the table (MySQL) * @method static generatedAs(string|Expression $expression = null) Create a SQL compliant identity column (PostgreSQL) * @method static index(string $indexName = null) Add an index * @method static nullable(bool $value = true) Allow NULL values to be inserted into the column * @method static persisted() Mark the computed generated column as persistent (SQL Server) * @method static primary() Add a primary index * @method static spatialIndex() Add a spatial index * @method static storedAs(string $expression) Create a stored generated column (MySQL) * @method static unique(string $indexName = null) Add a unique index * @method static unsigned() Set the INTEGER column as UNSIGNED (MySQL) * @method static useCurrent() Set the TIMESTAMP column to use CURRENT_TIMESTAMP as default value * @method static virtualAs(string $expression) Create a virtual generated column (MySQL) */ class ColumnDefinition extends Fluent { // }
5673342bfe63fb18549623856660a94319929c69
[ "PHP" ]
1
PHP
vlakoff/framework
46084d946cdcd1ae1f32fc87a4f1cc9e3a5bccf6
6fe9b9df9a7c460c8cbf60de09e7cc14a34e0342
refs/heads/master
<file_sep>sudo apt install sysstat net-tools -y<file_sep>def test_interfaces_up(collected_data): for key, value in collected_data['interfaces'].items(): assert 'UP' in value def test_default_route_present(collected_data): assert collected_data['default_route'] def test_processor_load_by_system(collected_data): assert float(collected_data['processor']['sys'].replace(',', '.')) < 75 def test_process_memory_consumption(collected_data): assert float(collected_data['process_info']['%mem']) < 30 def test_running_processes_list(collected_data): assert len(collected_data['process_list']) < 1000 def test_cron_running(collected_data): assert collected_data['cron_running'] def test_port_is_free(collected_data): for key, value in collected_data['ports_in_use'].items(): assert not value def test_package_not_alpha(collected_data): for key, value in collected_data['package_versions'].items(): assert 'alpha' not in value.casefold() def test_files_present(collected_data): assert collected_data['files'] def test_directory_not_root(collected_data): assert collected_data['current_directory'] != '/' def test_kernel_not_outdated(collected_data): assert float(collected_data['kernel_version'].rsplit('.', 1)[0]) > 5.1 def test_os_version_reported(collected_data): assert collected_data['os_version'] <file_sep>pytest==5.4.*<file_sep># Homework 26 ДЗ по взаимодействию с ОС Linux из Python ## Установка Для установки необходимых системных пакетов выполнить из корня репозитория команду `bash system_requirements.sh` Для установки pytest выполнить команду `python3 -m pip install pytest` ## Запуск Для вывода информации о системе выполнить команду `python3 system_info.py {params}`, где вместо "params" указать нужные параметры Для запуска тестов выполнить `python3 -m pytest test_os.py {params}` ### Параметры `--pid` -- ID запущенного процесса, о котором будет выведена или проверена тестом информация. Обязательный параметр `--port` -- порт, доступность которого будет проверена. По умолчанию 8000. `--package` -- системный пакет для проверки версии. Обязательный параметр. `--path` -- путь к папке, в которой будет проверено наличие файлов. Обязательный параметр.<file_sep>import argparse from info_collector import SystemInfoCollector parser = argparse.ArgumentParser() parser.add_argument('--pid', required=True, help='PID to show info about') parser.add_argument('--port', default='8000', help='Port to show state of or test') parser.add_argument('--package', required=True, help='Package name to show version of.') parser.add_argument( '--path', required=True, help='Path to show files from. Necessary if files_list or all params selected', ) args = parser.parse_args() data = SystemInfoCollector().get_data( pid=args.pid, package=args.package, path=args.path, port=args.port ) for data_field in data: if isinstance(data[data_field], dict): print(f'{data_field}:') for key, value in data[data_field].items(): print(f'{key}: {value}') print() elif isinstance(data[data_field], list): print(f'{data_field}:') for value in data[data_field]: print(value) print() else: print(f'{data_field}: {data[data_field]}\n') <file_sep>import os import re import subprocess class SystemInfoCollector: info = {} def _get_network_info(self): info = re.finditer( r'(\w{2,7}): flags=\d{1,4}<(.*)>', subprocess.run(['ifconfig'], capture_output=True).stdout.decode(), ) result = {iface.group(1): iface.group(2).split(',') for iface in info} self.info['interfaces'] = result def _get_default_route(self): process = subprocess.Popen(['ip', 'route'], stdout=subprocess.PIPE) self.info['default_route'] = ( subprocess.check_output(['grep', 'default'], stdin=process.stdout).decode().strip() ) def _get_cpu_info(self): process = subprocess.Popen(['mpstat'], stdout=subprocess.PIPE) stats = subprocess.check_output(['grep', 'all'], stdin=process.stdout).decode().split() self.info['processor'] = { 'usr': stats[2], 'nice': stats[3], 'sys': stats[4], 'iowait': stats[5], 'irq': stats[6], 'soft': stats[7], 'steal': stats[8], 'guest': stats[9], 'gnice': stats[10], 'idle': stats[11], } def _get_process_info(self, pid: str): process = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) stats = ( subprocess.check_output(['grep', pid], stdin=process.stdout) .decode() .strip() .split('\n') ) for line in stats: line = line.split() if line[1] != pid: continue else: self.info['process_info'] = { 'user': line[0], 'pid': line[1], '%cpu': line[2], '%mem': line[3], 'vsz': line[4], 'rss': line[5], 'tty': line[6], 'stat': line[7], 'start': line[8], 'time': line[9], 'command': ' '.join(line[10:]), } return self.info['process_info'] = None def _get_process_list(self): self.info['process_list'] = subprocess.check_output(['ps', 'aux']).decode().split('\n')[1:] def _get_network_interface_stats(self): stats = subprocess.check_output(['netstat', '-i']).decode().split('\n')[2:] self.info['network_interface_stats'] = [] for line in stats: line = line.split() self.info['network_interface_stats'].append( { 'interface': line[0], 'mtu': line[1], 'rx-ok': line[2], 'rx-err': line[3], 'rx-drp': line[4], 'rx-ovr': line[5], 'tx-ok': line[6], 'tx-err': line[7], 'tx-drp': line[8], 'tx-ovr': line[9], 'flags': line[10], } ) def _get_cron_service_status(self): services = subprocess.check_output(['service', '--status-all']).decode().split('\n') for service in services: service = service.split() if 'cron' in service: self.info['cron_running'] = '+' in service def _get_port_status(self, port: str): process = subprocess.Popen(['ss', '-tulpn'], stdout=subprocess.PIPE) port_in_use = subprocess.check_output( [f'grep tcp.*{port} || true'], stdin=process.stdout, shell=True ).decode() self.info['ports_in_use'] = {port: bool(port_in_use)} def _get_package_version(self, package: str): process = subprocess.Popen(['apt', 'show', package], stdout=subprocess.PIPE) version = ( subprocess.check_output(['grep', f'Version:'], stdin=process.stdout) .decode() .split()[1] ) self.info['package_versions'] = {package: version} def _get_files_in_path(self, path: str): process = subprocess.Popen(['ls', '-p', path], stdout=subprocess.PIPE) files = ( subprocess.check_output(['grep -v / || true'], shell=True, stdin=process.stdout) .decode() .split() ) self.info['files'] = files def _get_current_directory(self): self.info['current_directory'] = os.getcwd() def _get_kernel_version(self): self.info['kernel_version'] = os.uname().release def _get_os_version(self): self.info['os_version'] = os.uname().version def get_data(self, pid: str, package: str, path: str, port: str) -> dict: self._get_network_info() self._get_default_route() self._get_cpu_info() self._get_process_info(pid) self._get_process_list() self._get_cron_service_status() self._get_port_status(port) self._get_package_version(package) self._get_files_in_path(path) self._get_current_directory() self._get_kernel_version() self._get_os_version() return self.info <file_sep>import pytest from info_collector import SystemInfoCollector def pytest_addoption(parser): parser.addoption('--pid', required=True, help='PID to show info about') parser.addoption('--port', default='8000', help='Port to show state of or test') parser.addoption('--package', required=True, help='Package name to show version of.') parser.addoption( '--path', required=True, help='Path to show files from. Necessary if files_list or all params selected', ) @pytest.fixture(scope='session') def collected_data(request): return SystemInfoCollector().get_data( pid=request.config.getoption('--pid'), package=request.config.getoption('--package'), path=request.config.getoption('--path'), port=request.config.getoption('--port'), )
4ea1e3fb0e31b4c67cc80fdd783b15974798e956
[ "Markdown", "Python", "Text", "Shell" ]
7
Shell
alex-rybin/otus-qa-automation-os-tests
bb47d553431dad322cbbd9b488e486a60fd2b12a
91d6fe3d4477f5b3d183c8df5217af3f536e4f31
refs/heads/main
<repo_name>promisepreston/devops_exercise_docker<file_sep>/python_stop_server.py # /usr/bin/python3 import boto3 ec2 = boto3.resource('ec2') instance = ec2.Instance('id') response = instance.stop( Force=True ) <file_sep>/python_start_server.py # /usr/bin/python3.8 import boto3 ec2 = boto3.resource('ec2') instance = ec2.Instance('id') response = instance.start( AdditionalInfo='string' ) <file_sep>/docker_containers.sh #!/bin/sh set -e GREEN='\033[0;32m' # Define Variables ARCA_MYSQL_ROOT_PASSWORD=<PASSWORD> # Create docker network echo "${GREEN}Creating arcapayments docker network" docker network inspect arcapayments >/dev/null 2>&1 || \ docker network create arcapayments # Create a data directory for the MySQL server on the host machine for data persistence echo "${GREEN}Creating MySQL data directory on the host" mkdir -p /var/lib/mysql # Provision kibana echo "${GREEN}Pulling kibana docker image" # Pull kibana image from dockerhub docker pull kibana:6.4.2 echo "${GREEN}Starting docker container for kibana" # Remove kibana container if it already exists docker rm -f kibana || true docker run --name kibana --network arcapayments -p 5601:5601 -d kibana:6.4.2 # Provision Nginx echo "${GREEN}Pulling nginx docker image" # Pull nginx image from dockerhub docker pull nginx:1.21.3 echo "${GREEN}Starting docker container for nginx" # Remove nginx container if it already exists docker rm -f nginx || true docker run --name nginx --network arcapayments -p 8082:8082 -d nginx:1.21.3 # Provision MySQL server echo "${GREEN}Pulling mysql docker image" # Pull mysql image from dockerhub docker pull mysql:8.0.26 echo "${GREEN}Starting docker container for mysql" # Remove mysql container if it already exists docker rm -f mysql || true docker run --name mysql -v /var/lib/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=ARCA_MYSQL_ROOT_PASSWORD --network arcapayments -p 3306:3306 -d mysql:8.0.26 <file_sep>/README.md # README ## Part A ## Question 1 - Using Docker and Bash Using bash script, Write a script that will automatically provision 3 docker containers running kibana version 6.4.2, nginx server, mysql server separately on each container. **Environment**: Docker CE, Ubuntu 18 Write a script, which will be: container A: kibana version 6.4.2 container B: nginx server container C: mysql server **Acceptance criteria**: Solution should be prepared as only one script, which creates three Docker images, run containers from them, configures Nginx. The three docker containers should be able to ping each other regardless of where they are being deployed. Provide a well documented steps for how to reproduce your work. ## Solution 1 First, ensure that you have the Ubuntu server/virtual machine setup. Next, setup Docker and other docker dependencies on the server by following the steps in the links below: [Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/) [Post-installation steps for Linux](https://docs.docker.com/engine/install/linux-postinstall/) You can confirm that docker is all setup by running the commands below: docker version # display docker version docker container ls # list all containers Next, run the `docker_containers.sh` script to create a docker network, create mysql data directory, pull the kibana, nginx and mysql docker images and start up corresponding containers for them using the command below: sh docker_containers.sh This should create a docker network, create mysql data directory, pull the kibana, nginx and mysql docker images and start up their corresponding containers. To confirm that everything is fine, run the command below: docker container ls Next, we need to test the ping connectivity among the containers. To achieve we do the below in all the running containers. First, we will access the containers using the command: docker container exec -it CONTAINER_ID bin/bash **Note**: You can get the individidual CONTAINER_IDs by running the command - `docker container ls`. Next, the following commands to install the ping package on each container: apt update apt install iputils-ping exit Finally, run the following commands to test the ping connectivity among the containers: docker exec -it nginx ping kibana docker exec -it nginx ping mysql docker exec -it mysql ping kibana docker exec -it mysql ping nginx docker exec -it kibana ping nginx docker exec -it kibana ping mysql To clean up everything run the commands below: docker rm -f nginx || true docker rm -f mysql || true docker rm -f kibana || true docker network rm arcapayments docker system prune -a ### Question 2 - Terraform with Python for Infrastructure Automation Write a CloudFormation Template to provision a server in a default VPC write a python script to start the provisioned server write a python script to stop the provisioned server ### Solution 2 To get the solutions below to run from your local machine be sure to install the **AWS CLI** on your local machine and authenticate with it using your credentials. The CloudFormation script to provision a server on a default VPC can be found in the `cloudformation_server.yml` file. You can also find the terraform equivalence in the `terraform_server.yml` file. The terraform script can be structured better into modules but time was a constraint. The python script to start and stop the provisioned server can be found in the `python_start.py` and `python_stop.py` files respectively. To run them you need to first install boto3 and other dependencies following th steps here - [Boto3 quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html). The scripts can be run thus using `python3`: /usr/bin/python3 python_start_server.py # start provisioned server /usr/bin/python3 python_sop_server.py stop # stop provisioned server **Note**: Ensure to replace the `id` variable with the corresponding instance id of the server instance that you want to start or stop.
635d1cfa48d59b8c52f90fa45826005ee18e8bce
[ "Markdown", "Python", "Shell" ]
4
Python
promisepreston/devops_exercise_docker
4d8ce54d548d5a28f2913f5ffed1eb705cb41e06
982066679a4afa7509b514e8214b0d3b31cd7bfe
refs/heads/master
<file_sep>/* soapStub.h Generated by gSOAP 2.8.32 for soap.h gSOAP XML Web services tools Copyright (C) 2000-2016, <NAME>, Genivia Inc. All Rights Reserved. The soapcpp2 tool and its generated software are released under the GPL. This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia Inc., <EMAIL> -------------------------------------------------------------------------------- */ #ifndef soapStub_H #define soapStub_H #include "stdsoap2.h" #if GSOAP_VERSION != 20832 # error "GSOAP VERSION 20832 MISMATCH IN GENERATED CODE VERSUS LIBRARY CODE: PLEASE REINSTALL PACKAGE" #endif /******************************************************************************\ * * * Types with Custom Serializers * * * \******************************************************************************/ /******************************************************************************\ * * * Classes, Structs and Unions * * * \******************************************************************************/ class ResponseBase; /* soap.h:8 */ class Data; /* soap.h:17 */ class DataArray; /* soap.h:22 */ class DataRep; /* soap.h:27 */ struct ns2__getDataResponse; /* soap.h:35 */ struct ns2__getData; /* soap.h:35 */ /* soap.h:8 */ #ifndef SOAP_TYPE_ResponseBase #define SOAP_TYPE_ResponseBase (7) /* Type ResponseBase is a recursive data type, (in)directly referencing itself through its (base or derived class) members */ /* complex XSD type 'ResponseBase': */ class SOAP_CMAC ResponseBase { public: /// Required element 'status' of XSD type 'xsd:boolean' bool status; /// Required element 'message' of XSD type 'xsd:string' std::string message; /// Required element 'dateTime' of XSD type 'xsd:string' std::string dateTime; public: /// Return unique type id SOAP_TYPE_ResponseBase virtual int soap_type(void) const { return SOAP_TYPE_ResponseBase; } /// (Re)set members to default values virtual void soap_default(struct soap*); /// Serialize object to prepare for SOAP 1.1/1.2 encoded output (or with SOAP_XML_GRAPH) by analyzing its (cyclic) structures virtual void soap_serialize(struct soap*) const; /// Output object in XML, compliant with SOAP 1.1 encoding style, return error code or SOAP_OK virtual int soap_put(struct soap*, const char *tag, const char *type) const; /// Output object in XML, with tag and optional id attribute and xsi:type, return error code or SOAP_OK virtual int soap_out(struct soap*, const char *tag, int id, const char *type) const; /// Get object from XML, compliant with SOAP 1.1 encoding style, return pointer to object or NULL on error virtual void *soap_get(struct soap*, const char *tag, const char *type); /// Get object from XML, with matching tag and type (NULL matches any tag and type), return pointer to object or NULL on error virtual void *soap_in(struct soap*, const char *tag, const char *type); /// Return a new object of type ResponseBase, default initialized and not managed by a soap context virtual ResponseBase *soap_alloc(void) const { return SOAP_NEW(ResponseBase); } public: /// Constructor with initializations ResponseBase() { status = (bool)0; } virtual ~ResponseBase() { } /// Friend allocator used by soap_new_ResponseBase(struct soap*, int) friend SOAP_FMAC1 ResponseBase * SOAP_FMAC2 soap_instantiate_ResponseBase(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:17 */ #ifndef SOAP_TYPE_Data #define SOAP_TYPE_Data (10) /* complex XSD type 'Data': */ class SOAP_CMAC Data { public: /// Required element 'dateTime' of XSD type 'xsd:string' std::string dateTime; /// Required element 'content' of XSD type 'xsd:string' std::string content; public: /// Return unique type id SOAP_TYPE_Data virtual int soap_type(void) const { return SOAP_TYPE_Data; } /// (Re)set members to default values virtual void soap_default(struct soap*); /// Serialize object to prepare for SOAP 1.1/1.2 encoded output (or with SOAP_XML_GRAPH) by analyzing its (cyclic) structures virtual void soap_serialize(struct soap*) const; /// Output object in XML, compliant with SOAP 1.1 encoding style, return error code or SOAP_OK virtual int soap_put(struct soap*, const char *tag, const char *type) const; /// Output object in XML, with tag and optional id attribute and xsi:type, return error code or SOAP_OK virtual int soap_out(struct soap*, const char *tag, int id, const char *type) const; /// Get object from XML, compliant with SOAP 1.1 encoding style, return pointer to object or NULL on error virtual void *soap_get(struct soap*, const char *tag, const char *type); /// Get object from XML, with matching tag and type (NULL matches any tag and type), return pointer to object or NULL on error virtual void *soap_in(struct soap*, const char *tag, const char *type); /// Return a new object of type Data, default initialized and not managed by a soap context virtual Data *soap_alloc(void) const { return SOAP_NEW(Data); } public: /// Constructor with initializations Data() { } virtual ~Data() { } /// Friend allocator used by soap_new_Data(struct soap*, int) friend SOAP_FMAC1 Data * SOAP_FMAC2 soap_instantiate_Data(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:22 */ #ifndef SOAP_TYPE_DataArray #define SOAP_TYPE_DataArray (11) /* complex XSD type 'DataArray': */ class SOAP_CMAC DataArray { public: /// Sequence of elements 'data' of XSD type 'Data' stored in dynamic array data of length __size int __size; Data *data; public: /// Return unique type id SOAP_TYPE_DataArray virtual int soap_type(void) const { return SOAP_TYPE_DataArray; } /// (Re)set members to default values virtual void soap_default(struct soap*); /// Serialize object to prepare for SOAP 1.1/1.2 encoded output (or with SOAP_XML_GRAPH) by analyzing its (cyclic) structures virtual void soap_serialize(struct soap*) const; /// Output object in XML, compliant with SOAP 1.1 encoding style, return error code or SOAP_OK virtual int soap_put(struct soap*, const char *tag, const char *type) const; /// Output object in XML, with tag and optional id attribute and xsi:type, return error code or SOAP_OK virtual int soap_out(struct soap*, const char *tag, int id, const char *type) const; /// Get object from XML, compliant with SOAP 1.1 encoding style, return pointer to object or NULL on error virtual void *soap_get(struct soap*, const char *tag, const char *type); /// Get object from XML, with matching tag and type (NULL matches any tag and type), return pointer to object or NULL on error virtual void *soap_in(struct soap*, const char *tag, const char *type); /// Return a new object of type DataArray, default initialized and not managed by a soap context virtual DataArray *soap_alloc(void) const { return SOAP_NEW(DataArray); } public: /// Constructor with initializations DataArray() { __size = 0; data = NULL; } virtual ~DataArray() { } /// Friend allocator used by soap_new_DataArray(struct soap*, int) friend SOAP_FMAC1 DataArray * SOAP_FMAC2 soap_instantiate_DataArray(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:27 */ #ifndef SOAP_TYPE_DataRep #define SOAP_TYPE_DataRep (13) /* Type DataRep is a recursive data type, (in)directly referencing itself through its (base or derived class) members */ /* complex XSD type 'DataRep': */ class SOAP_CMAC DataRep : public ResponseBase { public: /// Required element 'quantity' of XSD type 'xsd:int' int quantity; /// Required element 'dataArray' of XSD type 'DataArray' DataArray dataArray; public: /// Return unique type id SOAP_TYPE_DataRep virtual int soap_type(void) const { return SOAP_TYPE_DataRep; } /// (Re)set members to default values virtual void soap_default(struct soap*); /// Serialize object to prepare for SOAP 1.1/1.2 encoded output (or with SOAP_XML_GRAPH) by analyzing its (cyclic) structures virtual void soap_serialize(struct soap*) const; /// Output object in XML, compliant with SOAP 1.1 encoding style, return error code or SOAP_OK virtual int soap_put(struct soap*, const char *tag, const char *type) const; /// Output object in XML, with tag and optional id attribute and xsi:type, return error code or SOAP_OK virtual int soap_out(struct soap*, const char *tag, int id, const char *type) const; /// Get object from XML, compliant with SOAP 1.1 encoding style, return pointer to object or NULL on error virtual void *soap_get(struct soap*, const char *tag, const char *type); /// Get object from XML, with matching tag and type (NULL matches any tag and type), return pointer to object or NULL on error virtual void *soap_in(struct soap*, const char *tag, const char *type); /// Return a new object of type DataRep, default initialized and not managed by a soap context virtual DataRep *soap_alloc(void) const { return SOAP_NEW(DataRep); } public: /// Constructor with initializations DataRep() { quantity = (int)0; } virtual ~DataRep() { } /// Friend allocator used by soap_new_DataRep(struct soap*, int) friend SOAP_FMAC1 DataRep * SOAP_FMAC2 soap_instantiate_DataRep(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:35 */ #ifndef SOAP_TYPE_ns2__getDataResponse #define SOAP_TYPE_ns2__getDataResponse (16) /* complex XSD type 'ns2:getDataResponse': */ struct ns2__getDataResponse { public: /** Required element 'result' of XSD type 'DataRep' */ DataRep result; public: /** Return unique type id SOAP_TYPE_ns2__getDataResponse */ int soap_type() const { return SOAP_TYPE_ns2__getDataResponse; } /** Constructor with member initializations */ ns2__getDataResponse() { } /** Friend allocator used by soap_new_ns2__getDataResponse(struct soap*, int) */ friend SOAP_FMAC1 ns2__getDataResponse * SOAP_FMAC2 soap_instantiate_ns2__getDataResponse(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:35 */ #ifndef SOAP_TYPE_ns2__getData #define SOAP_TYPE_ns2__getData (17) /* complex XSD type 'ns2:getData': */ struct ns2__getData { public: /** Required element 'name' of XSD type 'xsd:string' */ std::string name; public: /** Return unique type id SOAP_TYPE_ns2__getData */ int soap_type() const { return SOAP_TYPE_ns2__getData; } /** Constructor with member initializations */ ns2__getData() { } /** Friend allocator used by soap_new_ns2__getData(struct soap*, int) */ friend SOAP_FMAC1 ns2__getData * SOAP_FMAC2 soap_instantiate_ns2__getData(struct soap*, int, const char*, const char*, size_t*); }; #endif /* soap.h:38 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Header #define SOAP_TYPE_SOAP_ENV__Header (18) /* SOAP_ENV__Header: */ struct SOAP_ENV__Header { public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Header */ int soap_type() const { return SOAP_TYPE_SOAP_ENV__Header; } /** Constructor with member initializations */ SOAP_ENV__Header() { } /** Friend allocator used by soap_new_SOAP_ENV__Header(struct soap*, int) */ friend SOAP_FMAC1 SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* soap.h:38 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Code #define SOAP_TYPE_SOAP_ENV__Code (19) /* Type SOAP_ENV__Code is a recursive data type, (in)directly referencing itself through its (base or derived class) members */ /* SOAP_ENV__Code: */ struct SOAP_ENV__Code { public: /** Optional element 'SOAP-ENV:Value' of XSD type 'xsd:QName' */ char *SOAP_ENV__Value; /** Optional element 'SOAP-ENV:Subcode' of XSD type 'SOAP-ENV:Code' */ struct SOAP_ENV__Code *SOAP_ENV__Subcode; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Code */ int soap_type() const { return SOAP_TYPE_SOAP_ENV__Code; } /** Constructor with member initializations */ SOAP_ENV__Code() { SOAP_ENV__Value = (char *)0; SOAP_ENV__Subcode = (struct SOAP_ENV__Code *)0; } /** Friend allocator used by soap_new_SOAP_ENV__Code(struct soap*, int) */ friend SOAP_FMAC1 SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* soap.h:38 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Detail #define SOAP_TYPE_SOAP_ENV__Detail (21) /* SOAP_ENV__Detail: */ struct SOAP_ENV__Detail { public: char *__any; /** Any type of element 'fault' assigned to fault with its SOAP_TYPE_T assigned to __type */ /** Do not create a cyclic data structure throught this member unless SOAP encoding or SOAP_XML_GRAPH are used for id-ref serialization */ int __type; void *fault; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Detail */ int soap_type() const { return SOAP_TYPE_SOAP_ENV__Detail; } /** Constructor with member initializations */ SOAP_ENV__Detail() { __any = (char *)0; __type = 0; fault = NULL; } /** Friend allocator used by soap_new_SOAP_ENV__Detail(struct soap*, int) */ friend SOAP_FMAC1 SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* soap.h:38 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Reason #define SOAP_TYPE_SOAP_ENV__Reason (24) /* SOAP_ENV__Reason: */ struct SOAP_ENV__Reason { public: /** Optional element 'SOAP-ENV:Text' of XSD type 'xsd:string' */ char *SOAP_ENV__Text; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Reason */ int soap_type() const { return SOAP_TYPE_SOAP_ENV__Reason; } /** Constructor with member initializations */ SOAP_ENV__Reason() { SOAP_ENV__Text = (char *)0; } /** Friend allocator used by soap_new_SOAP_ENV__Reason(struct soap*, int) */ friend SOAP_FMAC1 SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* soap.h:38 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Fault #define SOAP_TYPE_SOAP_ENV__Fault (25) /* SOAP_ENV__Fault: */ struct SOAP_ENV__Fault { public: /** Optional element 'faultcode' of XSD type 'xsd:QName' */ char *faultcode; /** Optional element 'faultstring' of XSD type 'xsd:string' */ char *faultstring; /** Optional element 'faultactor' of XSD type 'xsd:string' */ char *faultactor; /** Optional element 'detail' of XSD type 'SOAP-ENV:Detail' */ struct SOAP_ENV__Detail *detail; /** Optional element 'SOAP-ENV:Code' of XSD type 'SOAP-ENV:Code' */ struct SOAP_ENV__Code *SOAP_ENV__Code; /** Optional element 'SOAP-ENV:Reason' of XSD type 'SOAP-ENV:Reason' */ struct SOAP_ENV__Reason *SOAP_ENV__Reason; /** Optional element 'SOAP-ENV:Node' of XSD type 'xsd:string' */ char *SOAP_ENV__Node; /** Optional element 'SOAP-ENV:Role' of XSD type 'xsd:string' */ char *SOAP_ENV__Role; /** Optional element 'SOAP-ENV:Detail' of XSD type 'SOAP-ENV:Detail' */ struct SOAP_ENV__Detail *SOAP_ENV__Detail; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Fault */ int soap_type() const { return SOAP_TYPE_SOAP_ENV__Fault; } /** Constructor with member initializations */ SOAP_ENV__Fault() { faultcode = (char *)0; faultstring = (char *)0; faultactor = (char *)0; detail = (struct SOAP_ENV__Detail *)0; SOAP_ENV__Code = (struct SOAP_ENV__Code *)0; SOAP_ENV__Reason = (struct SOAP_ENV__Reason *)0; SOAP_ENV__Node = (char *)0; SOAP_ENV__Role = (char *)0; SOAP_ENV__Detail = (struct SOAP_ENV__Detail *)0; } /** Friend allocator used by soap_new_SOAP_ENV__Fault(struct soap*, int) */ friend SOAP_FMAC1 SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /******************************************************************************\ * * * Typedefs * * * \******************************************************************************/ /* soap.h:8 */ #ifndef SOAP_TYPE__QName #define SOAP_TYPE__QName (5) typedef char *_QName; #endif /* soap.h:8 */ #ifndef SOAP_TYPE__XML #define SOAP_TYPE__XML (6) typedef char *_XML; #endif /******************************************************************************\ * * * Serializable Types * * * \******************************************************************************/ /* char has binding name 'byte' for type 'xsd:byte' */ #ifndef SOAP_TYPE_byte #define SOAP_TYPE_byte (3) #endif /* int has binding name 'int' for type 'xsd:int' */ #ifndef SOAP_TYPE_int #define SOAP_TYPE_int (1) #endif /* bool has binding name 'bool' for type 'xsd:boolean' */ #ifndef SOAP_TYPE_bool #define SOAP_TYPE_bool (8) #endif /* DataRep has binding name 'DataRep' for type 'DataRep' */ #ifndef SOAP_TYPE_DataRep #define SOAP_TYPE_DataRep (13) #endif /* DataArray has binding name 'DataArray' for type 'DataArray' */ #ifndef SOAP_TYPE_DataArray #define SOAP_TYPE_DataArray (11) #endif /* Data has binding name 'Data' for type 'Data' */ #ifndef SOAP_TYPE_Data #define SOAP_TYPE_Data (10) #endif /* std::string has binding name 'std__string' for type 'xsd:string' */ #ifndef SOAP_TYPE_std__string #define SOAP_TYPE_std__string (9) #endif /* ResponseBase has binding name 'ResponseBase' for type 'ResponseBase' */ #ifndef SOAP_TYPE_ResponseBase #define SOAP_TYPE_ResponseBase (7) #endif /* struct SOAP_ENV__Fault has binding name 'SOAP_ENV__Fault' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Fault #define SOAP_TYPE_SOAP_ENV__Fault (25) #endif /* struct SOAP_ENV__Reason has binding name 'SOAP_ENV__Reason' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Reason #define SOAP_TYPE_SOAP_ENV__Reason (24) #endif /* struct SOAP_ENV__Detail has binding name 'SOAP_ENV__Detail' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Detail #define SOAP_TYPE_SOAP_ENV__Detail (21) #endif /* struct SOAP_ENV__Code has binding name 'SOAP_ENV__Code' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Code #define SOAP_TYPE_SOAP_ENV__Code (19) #endif /* struct SOAP_ENV__Header has binding name 'SOAP_ENV__Header' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Header #define SOAP_TYPE_SOAP_ENV__Header (18) #endif /* struct ns2__getData has binding name 'ns2__getData' for type 'ns2:getData' */ #ifndef SOAP_TYPE_ns2__getData #define SOAP_TYPE_ns2__getData (17) #endif /* struct ns2__getDataResponse has binding name 'ns2__getDataResponse' for type 'ns2:getDataResponse' */ #ifndef SOAP_TYPE_ns2__getDataResponse #define SOAP_TYPE_ns2__getDataResponse (16) #endif /* struct SOAP_ENV__Reason * has binding name 'PointerToSOAP_ENV__Reason' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason #define SOAP_TYPE_PointerToSOAP_ENV__Reason (27) #endif /* struct SOAP_ENV__Detail * has binding name 'PointerToSOAP_ENV__Detail' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail #define SOAP_TYPE_PointerToSOAP_ENV__Detail (26) #endif /* struct SOAP_ENV__Code * has binding name 'PointerToSOAP_ENV__Code' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Code #define SOAP_TYPE_PointerToSOAP_ENV__Code (20) #endif /* Data * has binding name 'PointerToData' for type 'Data' */ #ifndef SOAP_TYPE_PointerToData #define SOAP_TYPE_PointerToData (12) #endif /* _XML has binding name '_XML' for type '' */ #ifndef SOAP_TYPE__XML #define SOAP_TYPE__XML (6) #endif /* _QName has binding name '_QName' for type 'xsd:QName' */ #ifndef SOAP_TYPE__QName #define SOAP_TYPE__QName (5) #endif /* char * has binding name 'string' for type 'xsd:string' */ #ifndef SOAP_TYPE_string #define SOAP_TYPE_string (4) #endif /******************************************************************************\ * * * Externals * * * \******************************************************************************/ #endif /* End of soapStub.h */ <file_sep> //gsoap ns2 service name: soap //gsoap ns2 service style: rpc //gsoap ns2 service encoding: encoded //gsoap ns2 service namespace: http://github.com/linuxxunil //gsoap ns2 schema namespace: urn:soap class ResponseBase { bool status; // Y,N std::string message; std::string dateTime; }; // getData class Data { std::string dateTime; std::string content; }; class DataArray { int __size; Data *data; }; class DataRep : protected ResponseBase { int quantity; DataArray dataArray; }; int ns2__getData( std::string name, DataRep &result ); <file_sep>/* soapH.h Generated by gSOAP 2.8.32 for soap.h gSOAP XML Web services tools Copyright (C) 2000-2016, <NAME>, Genivia Inc. All Rights Reserved. The soapcpp2 tool and its generated software are released under the GPL. This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia Inc., <EMAIL> -------------------------------------------------------------------------------- */ #ifndef soapH_H #define soapH_H #include "soapStub.h" #ifndef WITH_NOIDREF #ifdef __cplusplus extern "C" { #endif SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap*, const void*, int); #ifdef __cplusplus } #endif SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap*); SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap*); #endif #ifdef __cplusplus extern "C" { #endif SOAP_FMAC3 void *SOAP_FMAC4 soap_getelement(struct soap*, int*); SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap*, const void*, const char*, int, int); #ifdef __cplusplus } #endif SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap*); SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap); SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap*, int, const char*, const char*, size_t*); SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist*); SOAP_FMAC3 int SOAP_FMAC4 soap_fbase(int, int); SOAP_FMAC3 void SOAP_FMAC4 soap_finsert(struct soap*, int, int, void*, size_t, const void*, void**); #ifndef SOAP_TYPE_byte_DEFINED #define SOAP_TYPE_byte_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap*, char *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap*, const char*, int, const char *, const char*); SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap*, const char*, char *, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap*, const char *, const char*, const char*); inline int soap_write_byte(struct soap *soap, char const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put_byte(soap, p, "byte", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap*, char *, const char*, const char*); inline int soap_read_byte(struct soap *soap, char *p) { if (p) { if (soap_begin_recv(soap) || soap_get_byte(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_int_DEFINED #define SOAP_TYPE_int_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap*, int *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap*, const char*, int, const int *, const char*); SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap*, const char*, int *, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap*, const int *, const char*, const char*); inline int soap_write_int(struct soap *soap, int const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put_int(soap, p, "int", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap*, int *, const char*, const char*); inline int soap_read_int(struct soap *soap, int *p) { if (p) { if (soap_begin_recv(soap) || soap_get_int(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_bool_DEFINED #define SOAP_TYPE_bool_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_bool(struct soap*, bool *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_bool(struct soap*, const char*, int, const bool *, const char*); SOAP_FMAC3S const char* SOAP_FMAC4S soap_bool2s(struct soap*, bool); SOAP_FMAC3 bool * SOAP_FMAC4 soap_in_bool(struct soap*, const char*, bool *, const char*); SOAP_FMAC3S int SOAP_FMAC4S soap_s2bool(struct soap*, const char*, bool *); inline bool * soap_new_bool(struct soap *soap, int n = -1) { return static_cast<bool *>(soap_malloc(soap, (n < 0 ? 1 : n) * sizeof(bool))); } SOAP_FMAC3 int SOAP_FMAC4 soap_put_bool(struct soap*, const bool *, const char*, const char*); inline int soap_write_bool(struct soap *soap, bool const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put_bool(soap, p, "boolean", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 bool * SOAP_FMAC4 soap_get_bool(struct soap*, bool *, const char*, const char*); inline int soap_read_bool(struct soap *soap, bool *p) { if (p) { if (soap_begin_recv(soap) || soap_get_bool(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_DataRep_DEFINED #define SOAP_TYPE_DataRep_DEFINED SOAP_FMAC3 int SOAP_FMAC4 soap_out_DataRep(struct soap*, const char*, int, const DataRep *, const char*); SOAP_FMAC3 DataRep * SOAP_FMAC4 soap_in_DataRep(struct soap*, const char*, DataRep *, const char*); SOAP_FMAC1 DataRep * SOAP_FMAC2 soap_instantiate_DataRep(struct soap*, int, const char*, const char*, size_t*); inline DataRep * soap_new_DataRep(struct soap *soap, int n = -1) { return soap_instantiate_DataRep(soap, n, NULL, NULL, NULL); } inline DataRep * soap_new_req_DataRep( struct soap *soap, int quantity, const DataArray& dataArray, bool status1, const std::string& message1, const std::string& dateTime1) { DataRep *_p = soap_new_DataRep(soap); if (_p) { _p->soap_default(soap); _p->DataRep::quantity = quantity; _p->DataRep::dataArray = dataArray; _p->ResponseBase::status = status1; _p->ResponseBase::message = message1; _p->ResponseBase::dateTime = dateTime1; } return _p; } inline DataRep * soap_new_set_DataRep( struct soap *soap, int quantity, const DataArray& dataArray, bool status1, const std::string& message1, const std::string& dateTime1) { DataRep *_p = soap_new_DataRep(soap); if (_p) { _p->soap_default(soap); _p->DataRep::quantity = quantity; _p->DataRep::dataArray = dataArray; _p->ResponseBase::status = status1; _p->ResponseBase::message = message1; _p->ResponseBase::dateTime = dateTime1; } return _p; } inline int soap_write_DataRep(struct soap *soap, DataRep const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (p->soap_serialize(soap), 0) || p->soap_put(soap, "DataRep", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 DataRep * SOAP_FMAC4 soap_get_DataRep(struct soap*, DataRep *, const char*, const char*); inline int soap_read_DataRep(struct soap *soap, DataRep *p) { if (p) { p->soap_default(soap); if (soap_begin_recv(soap) || soap_get_DataRep(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_DataArray_DEFINED #define SOAP_TYPE_DataArray_DEFINED SOAP_FMAC3 int SOAP_FMAC4 soap_out_DataArray(struct soap*, const char*, int, const DataArray *, const char*); SOAP_FMAC3 DataArray * SOAP_FMAC4 soap_in_DataArray(struct soap*, const char*, DataArray *, const char*); SOAP_FMAC1 DataArray * SOAP_FMAC2 soap_instantiate_DataArray(struct soap*, int, const char*, const char*, size_t*); inline DataArray * soap_new_DataArray(struct soap *soap, int n = -1) { return soap_instantiate_DataArray(soap, n, NULL, NULL, NULL); } inline DataArray * soap_new_req_DataArray( struct soap *soap, int __size, Data *data) { DataArray *_p = soap_new_DataArray(soap); if (_p) { _p->soap_default(soap); _p->DataArray::__size = __size; _p->DataArray::data = data; } return _p; } inline DataArray * soap_new_set_DataArray( struct soap *soap, int __size, Data *data) { DataArray *_p = soap_new_DataArray(soap); if (_p) { _p->soap_default(soap); _p->DataArray::__size = __size; _p->DataArray::data = data; } return _p; } inline int soap_write_DataArray(struct soap *soap, DataArray const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (p->soap_serialize(soap), 0) || p->soap_put(soap, "DataArray", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 DataArray * SOAP_FMAC4 soap_get_DataArray(struct soap*, DataArray *, const char*, const char*); inline int soap_read_DataArray(struct soap *soap, DataArray *p) { if (p) { p->soap_default(soap); if (soap_begin_recv(soap) || soap_get_DataArray(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_Data_DEFINED #define SOAP_TYPE_Data_DEFINED SOAP_FMAC3 int SOAP_FMAC4 soap_out_Data(struct soap*, const char*, int, const Data *, const char*); SOAP_FMAC3 Data * SOAP_FMAC4 soap_in_Data(struct soap*, const char*, Data *, const char*); SOAP_FMAC1 Data * SOAP_FMAC2 soap_instantiate_Data(struct soap*, int, const char*, const char*, size_t*); inline Data * soap_new_Data(struct soap *soap, int n = -1) { return soap_instantiate_Data(soap, n, NULL, NULL, NULL); } inline Data * soap_new_req_Data( struct soap *soap, const std::string& dateTime, const std::string& content) { Data *_p = soap_new_Data(soap); if (_p) { _p->soap_default(soap); _p->Data::dateTime = dateTime; _p->Data::content = content; } return _p; } inline Data * soap_new_set_Data( struct soap *soap, const std::string& dateTime, const std::string& content) { Data *_p = soap_new_Data(soap); if (_p) { _p->soap_default(soap); _p->Data::dateTime = dateTime; _p->Data::content = content; } return _p; } inline int soap_write_Data(struct soap *soap, Data const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (p->soap_serialize(soap), 0) || p->soap_put(soap, "Data", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 Data * SOAP_FMAC4 soap_get_Data(struct soap*, Data *, const char*, const char*); inline int soap_read_Data(struct soap *soap, Data *p) { if (p) { p->soap_default(soap); if (soap_begin_recv(soap) || soap_get_Data(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_std__string_DEFINED #define SOAP_TYPE_std__string_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_std__string(struct soap*, std::string *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_std__string(struct soap*, const std::string *); #define soap_std__string2s(soap, a) ((a).c_str()) SOAP_FMAC3 int SOAP_FMAC4 soap_out_std__string(struct soap*, const char*, int, const std::string*, const char*); #define soap_s2std__string(soap, s, a) soap_s2stdchar((soap), (s), (a), 0, -1, NULL) SOAP_FMAC3 std::string * SOAP_FMAC4 soap_in_std__string(struct soap*, const char*, std::string*, const char*); SOAP_FMAC1 std::string * SOAP_FMAC2 soap_instantiate_std__string(struct soap*, int, const char*, const char*, size_t*); inline std::string * soap_new_std__string(struct soap *soap, int n = -1) { return soap_instantiate_std__string(soap, n, NULL, NULL, NULL); } inline std::string * soap_new_req_std__string( struct soap *soap) { std::string *_p = soap_new_std__string(soap); if (_p) { soap_default_std__string(soap, _p); } return _p; } inline std::string * soap_new_set_std__string( struct soap *soap) { std::string *_p = soap_new_std__string(soap); if (_p) { soap_default_std__string(soap, _p); } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_std__string(struct soap*, const std::string *, const char*, const char*); inline int soap_write_std__string(struct soap *soap, std::string const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put_std__string(soap, p, "string", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 std::string * SOAP_FMAC4 soap_get_std__string(struct soap*, std::string *, const char*, const char*); inline int soap_read_std__string(struct soap *soap, std::string *p) { if (p) { if (soap_begin_recv(soap) || soap_get_std__string(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_ResponseBase_DEFINED #define SOAP_TYPE_ResponseBase_DEFINED SOAP_FMAC3 int SOAP_FMAC4 soap_out_ResponseBase(struct soap*, const char*, int, const ResponseBase *, const char*); SOAP_FMAC3 ResponseBase * SOAP_FMAC4 soap_in_ResponseBase(struct soap*, const char*, ResponseBase *, const char*); SOAP_FMAC1 ResponseBase * SOAP_FMAC2 soap_instantiate_ResponseBase(struct soap*, int, const char*, const char*, size_t*); inline ResponseBase * soap_new_ResponseBase(struct soap *soap, int n = -1) { return soap_instantiate_ResponseBase(soap, n, NULL, NULL, NULL); } inline ResponseBase * soap_new_req_ResponseBase( struct soap *soap, bool status, const std::string& message, const std::string& dateTime) { ResponseBase *_p = soap_new_ResponseBase(soap); if (_p) { _p->soap_default(soap); _p->ResponseBase::status = status; _p->ResponseBase::message = message; _p->ResponseBase::dateTime = dateTime; } return _p; } inline ResponseBase * soap_new_set_ResponseBase( struct soap *soap, bool status, const std::string& message, const std::string& dateTime) { ResponseBase *_p = soap_new_ResponseBase(soap); if (_p) { _p->soap_default(soap); _p->ResponseBase::status = status; _p->ResponseBase::message = message; _p->ResponseBase::dateTime = dateTime; } return _p; } inline int soap_write_ResponseBase(struct soap *soap, ResponseBase const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (p->soap_serialize(soap), 0) || p->soap_put(soap, "ResponseBase", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 ResponseBase * SOAP_FMAC4 soap_get_ResponseBase(struct soap*, ResponseBase *, const char*, const char*); inline int soap_read_ResponseBase(struct soap *soap, ResponseBase *p) { if (p) { p->soap_default(soap); if (soap_begin_recv(soap) || soap_get_ResponseBase(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Fault_DEFINED #define SOAP_TYPE_SOAP_ENV__Fault_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap*, const char*, int, const struct SOAP_ENV__Fault *, const char*); SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap*, const char*, struct SOAP_ENV__Fault *, const char*); SOAP_FMAC1 struct SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*); inline struct SOAP_ENV__Fault * soap_new_SOAP_ENV__Fault(struct soap *soap, int n = -1) { return soap_instantiate_SOAP_ENV__Fault(soap, n, NULL, NULL, NULL); } inline struct SOAP_ENV__Fault * soap_new_req_SOAP_ENV__Fault( struct soap *soap) { struct SOAP_ENV__Fault *_p = soap_new_SOAP_ENV__Fault(soap); if (_p) { soap_default_SOAP_ENV__Fault(soap, _p); } return _p; } inline struct SOAP_ENV__Fault * soap_new_set_SOAP_ENV__Fault( struct soap *soap, char *faultcode, char *faultstring, char *faultactor, struct SOAP_ENV__Detail *detail, struct SOAP_ENV__Code *SOAP_ENV__Code, struct SOAP_ENV__Reason *SOAP_ENV__Reason, char *SOAP_ENV__Node, char *SOAP_ENV__Role, struct SOAP_ENV__Detail *SOAP_ENV__Detail) { struct SOAP_ENV__Fault *_p = soap_new_SOAP_ENV__Fault(soap); if (_p) { soap_default_SOAP_ENV__Fault(soap, _p); _p->faultcode = faultcode; _p->faultstring = faultstring; _p->faultactor = faultactor; _p->detail = detail; _p->SOAP_ENV__Code = SOAP_ENV__Code; _p->SOAP_ENV__Reason = SOAP_ENV__Reason; _p->SOAP_ENV__Node = SOAP_ENV__Node; _p->SOAP_ENV__Role = SOAP_ENV__Role; _p->SOAP_ENV__Detail = SOAP_ENV__Detail; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *, const char*, const char*); inline int soap_write_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_SOAP_ENV__Fault(soap, p), 0) || soap_put_SOAP_ENV__Fault(soap, p, "SOAP-ENV:Fault", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *, const char*, const char*); inline int soap_read_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p) { if (p) { soap_default_SOAP_ENV__Fault(soap, p); if (soap_begin_recv(soap) || soap_get_SOAP_ENV__Fault(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Reason_DEFINED #define SOAP_TYPE_SOAP_ENV__Reason_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap*, const char*, int, const struct SOAP_ENV__Reason *, const char*); SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason *, const char*); SOAP_FMAC1 struct SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*); inline struct SOAP_ENV__Reason * soap_new_SOAP_ENV__Reason(struct soap *soap, int n = -1) { return soap_instantiate_SOAP_ENV__Reason(soap, n, NULL, NULL, NULL); } inline struct SOAP_ENV__Reason * soap_new_req_SOAP_ENV__Reason( struct soap *soap) { struct SOAP_ENV__Reason *_p = soap_new_SOAP_ENV__Reason(soap); if (_p) { soap_default_SOAP_ENV__Reason(soap, _p); } return _p; } inline struct SOAP_ENV__Reason * soap_new_set_SOAP_ENV__Reason( struct soap *soap, char *SOAP_ENV__Text) { struct SOAP_ENV__Reason *_p = soap_new_SOAP_ENV__Reason(soap); if (_p) { soap_default_SOAP_ENV__Reason(soap, _p); _p->SOAP_ENV__Text = SOAP_ENV__Text; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *, const char*, const char*); inline int soap_write_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_SOAP_ENV__Reason(soap, p), 0) || soap_put_SOAP_ENV__Reason(soap, p, "SOAP-ENV:Reason", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *, const char*, const char*); inline int soap_read_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p) { if (p) { soap_default_SOAP_ENV__Reason(soap, p); if (soap_begin_recv(soap) || soap_get_SOAP_ENV__Reason(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Detail_DEFINED #define SOAP_TYPE_SOAP_ENV__Detail_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap*, const char*, int, const struct SOAP_ENV__Detail *, const char*); SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail *, const char*); SOAP_FMAC1 struct SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*); inline struct SOAP_ENV__Detail * soap_new_SOAP_ENV__Detail(struct soap *soap, int n = -1) { return soap_instantiate_SOAP_ENV__Detail(soap, n, NULL, NULL, NULL); } inline struct SOAP_ENV__Detail * soap_new_req_SOAP_ENV__Detail( struct soap *soap, int __type, void *fault) { struct SOAP_ENV__Detail *_p = soap_new_SOAP_ENV__Detail(soap); if (_p) { soap_default_SOAP_ENV__Detail(soap, _p); _p->__type = __type; _p->fault = fault; } return _p; } inline struct SOAP_ENV__Detail * soap_new_set_SOAP_ENV__Detail( struct soap *soap, char *__any, int __type, void *fault) { struct SOAP_ENV__Detail *_p = soap_new_SOAP_ENV__Detail(soap); if (_p) { soap_default_SOAP_ENV__Detail(soap, _p); _p->__any = __any; _p->__type = __type; _p->fault = fault; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *, const char*, const char*); inline int soap_write_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_SOAP_ENV__Detail(soap, p), 0) || soap_put_SOAP_ENV__Detail(soap, p, "SOAP-ENV:Detail", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *, const char*, const char*); inline int soap_read_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p) { if (p) { soap_default_SOAP_ENV__Detail(soap, p); if (soap_begin_recv(soap) || soap_get_SOAP_ENV__Detail(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Code_DEFINED #define SOAP_TYPE_SOAP_ENV__Code_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap*, const char*, int, const struct SOAP_ENV__Code *, const char*); SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code *, const char*); SOAP_FMAC1 struct SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*); inline struct SOAP_ENV__Code * soap_new_SOAP_ENV__Code(struct soap *soap, int n = -1) { return soap_instantiate_SOAP_ENV__Code(soap, n, NULL, NULL, NULL); } inline struct SOAP_ENV__Code * soap_new_req_SOAP_ENV__Code( struct soap *soap) { struct SOAP_ENV__Code *_p = soap_new_SOAP_ENV__Code(soap); if (_p) { soap_default_SOAP_ENV__Code(soap, _p); } return _p; } inline struct SOAP_ENV__Code * soap_new_set_SOAP_ENV__Code( struct soap *soap, char *SOAP_ENV__Value, struct SOAP_ENV__Code *SOAP_ENV__Subcode) { struct SOAP_ENV__Code *_p = soap_new_SOAP_ENV__Code(soap); if (_p) { soap_default_SOAP_ENV__Code(soap, _p); _p->SOAP_ENV__Value = SOAP_ENV__Value; _p->SOAP_ENV__Subcode = SOAP_ENV__Subcode; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *, const char*, const char*); inline int soap_write_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_SOAP_ENV__Code(soap, p), 0) || soap_put_SOAP_ENV__Code(soap, p, "SOAP-ENV:Code", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *, const char*, const char*); inline int soap_read_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p) { if (p) { soap_default_SOAP_ENV__Code(soap, p); if (soap_begin_recv(soap) || soap_get_SOAP_ENV__Code(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Header_DEFINED #define SOAP_TYPE_SOAP_ENV__Header_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap*, const char*, int, const struct SOAP_ENV__Header *, const char*); SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap*, const char*, struct SOAP_ENV__Header *, const char*); SOAP_FMAC1 struct SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*); inline struct SOAP_ENV__Header * soap_new_SOAP_ENV__Header(struct soap *soap, int n = -1) { return soap_instantiate_SOAP_ENV__Header(soap, n, NULL, NULL, NULL); } inline struct SOAP_ENV__Header * soap_new_req_SOAP_ENV__Header( struct soap *soap) { struct SOAP_ENV__Header *_p = soap_new_SOAP_ENV__Header(soap); if (_p) { soap_default_SOAP_ENV__Header(soap, _p); } return _p; } inline struct SOAP_ENV__Header * soap_new_set_SOAP_ENV__Header( struct soap *soap) { struct SOAP_ENV__Header *_p = soap_new_SOAP_ENV__Header(soap); if (_p) { soap_default_SOAP_ENV__Header(soap, _p); } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *, const char*, const char*); inline int soap_write_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_SOAP_ENV__Header(soap, p), 0) || soap_put_SOAP_ENV__Header(soap, p, "SOAP-ENV:Header", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *, const char*, const char*); inline int soap_read_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p) { if (p) { soap_default_SOAP_ENV__Header(soap, p); if (soap_begin_recv(soap) || soap_get_SOAP_ENV__Header(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif #ifndef SOAP_TYPE_ns2__getData_DEFINED #define SOAP_TYPE_ns2__getData_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns2__getData(struct soap*, struct ns2__getData *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns2__getData(struct soap*, const struct ns2__getData *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns2__getData(struct soap*, const char*, int, const struct ns2__getData *, const char*); SOAP_FMAC3 struct ns2__getData * SOAP_FMAC4 soap_in_ns2__getData(struct soap*, const char*, struct ns2__getData *, const char*); SOAP_FMAC1 struct ns2__getData * SOAP_FMAC2 soap_instantiate_ns2__getData(struct soap*, int, const char*, const char*, size_t*); inline struct ns2__getData * soap_new_ns2__getData(struct soap *soap, int n = -1) { return soap_instantiate_ns2__getData(soap, n, NULL, NULL, NULL); } inline struct ns2__getData * soap_new_req_ns2__getData( struct soap *soap, const std::string& name) { struct ns2__getData *_p = soap_new_ns2__getData(soap); if (_p) { soap_default_ns2__getData(soap, _p); _p->name = name; } return _p; } inline struct ns2__getData * soap_new_set_ns2__getData( struct soap *soap, const std::string& name) { struct ns2__getData *_p = soap_new_ns2__getData(soap); if (_p) { soap_default_ns2__getData(soap, _p); _p->name = name; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns2__getData(struct soap*, const struct ns2__getData *, const char*, const char*); inline int soap_write_ns2__getData(struct soap *soap, struct ns2__getData const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_ns2__getData(soap, p), 0) || soap_put_ns2__getData(soap, p, "ns2:getData", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct ns2__getData * SOAP_FMAC4 soap_get_ns2__getData(struct soap*, struct ns2__getData *, const char*, const char*); inline int soap_read_ns2__getData(struct soap *soap, struct ns2__getData *p) { if (p) { soap_default_ns2__getData(soap, p); if (soap_begin_recv(soap) || soap_get_ns2__getData(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_ns2__getDataResponse_DEFINED #define SOAP_TYPE_ns2__getDataResponse_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns2__getDataResponse(struct soap*, struct ns2__getDataResponse *); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns2__getDataResponse(struct soap*, const struct ns2__getDataResponse *); SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns2__getDataResponse(struct soap*, const char*, int, const struct ns2__getDataResponse *, const char*); SOAP_FMAC3 struct ns2__getDataResponse * SOAP_FMAC4 soap_in_ns2__getDataResponse(struct soap*, const char*, struct ns2__getDataResponse *, const char*); SOAP_FMAC1 struct ns2__getDataResponse * SOAP_FMAC2 soap_instantiate_ns2__getDataResponse(struct soap*, int, const char*, const char*, size_t*); inline struct ns2__getDataResponse * soap_new_ns2__getDataResponse(struct soap *soap, int n = -1) { return soap_instantiate_ns2__getDataResponse(soap, n, NULL, NULL, NULL); } inline struct ns2__getDataResponse * soap_new_req_ns2__getDataResponse( struct soap *soap, const DataRep& result) { struct ns2__getDataResponse *_p = soap_new_ns2__getDataResponse(soap); if (_p) { soap_default_ns2__getDataResponse(soap, _p); _p->result = result; } return _p; } inline struct ns2__getDataResponse * soap_new_set_ns2__getDataResponse( struct soap *soap, const DataRep& result) { struct ns2__getDataResponse *_p = soap_new_ns2__getDataResponse(soap); if (_p) { soap_default_ns2__getDataResponse(soap, _p); _p->result = result; } return _p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns2__getDataResponse(struct soap*, const struct ns2__getDataResponse *, const char*, const char*); inline int soap_write_ns2__getDataResponse(struct soap *soap, struct ns2__getDataResponse const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || (soap_serialize_ns2__getDataResponse(soap, p), 0) || soap_put_ns2__getDataResponse(soap, p, "ns2:getDataResponse", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 struct ns2__getDataResponse * SOAP_FMAC4 soap_get_ns2__getDataResponse(struct soap*, struct ns2__getDataResponse *, const char*, const char*); inline int soap_read_ns2__getDataResponse(struct soap *soap, struct ns2__getDataResponse *p) { if (p) { soap_default_ns2__getDataResponse(soap, p); if (soap_begin_recv(soap) || soap_get_ns2__getDataResponse(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason_DEFINED #define SOAP_TYPE_PointerToSOAP_ENV__Reason_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*); SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap*, const char *, int, struct SOAP_ENV__Reason *const*, const char *); SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*, const char*, const char*); SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason **, const char*, const char*); #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail_DEFINED #define SOAP_TYPE_PointerToSOAP_ENV__Detail_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*); SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap*, const char *, int, struct SOAP_ENV__Detail *const*, const char *); SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*, const char*, const char*); SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail **, const char*, const char*); #endif #endif #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_PointerToSOAP_ENV__Code_DEFINED #define SOAP_TYPE_PointerToSOAP_ENV__Code_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*); SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap*, const char *, int, struct SOAP_ENV__Code *const*, const char *); SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*, const char*, const char*); SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code **, const char*, const char*); #endif #endif #ifndef SOAP_TYPE_PointerToData_DEFINED #define SOAP_TYPE_PointerToData_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToData(struct soap*, Data *const*); SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToData(struct soap*, const char *, int, Data *const*, const char *); SOAP_FMAC3 Data ** SOAP_FMAC4 soap_in_PointerToData(struct soap*, const char*, Data **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToData(struct soap*, Data *const*, const char*, const char*); SOAP_FMAC3 Data ** SOAP_FMAC4 soap_get_PointerToData(struct soap*, Data **, const char*, const char*); #endif #ifndef SOAP_TYPE__XML_DEFINED #define SOAP_TYPE__XML_DEFINED #endif #ifndef SOAP_TYPE__QName_DEFINED #define SOAP_TYPE__QName_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap*, char **); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap*, char *const*); #define soap__QName2s(soap, a) soap_QName2s(soap, (a)) SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap*, const char*, int, char*const*, const char*); #define soap_s2_QName(soap, s, a) soap_s2QName((soap), (s), (char**)(a), 0, -1, NULL) SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap*, const char*, char **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap*, char *const*, const char*, const char*); inline int soap_write__QName(struct soap *soap, char *const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put__QName(soap, p, "QName", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap*, char **, const char*, const char*); inline int soap_read__QName(struct soap *soap, char **p) { if (p) { if (soap_begin_recv(soap) || soap_get__QName(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #ifndef SOAP_TYPE_string_DEFINED #define SOAP_TYPE_string_DEFINED SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap*, char **); SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap*, char *const*); #define soap_string2s(soap, a) (a) SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap*, const char*, int, char*const*, const char*); #define soap_s2string(soap, s, a) soap_s2char((soap), (s), (char**)(a), 0, -1, NULL) SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap*, const char*, char **, const char*); SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap*, char *const*, const char*, const char*); inline int soap_write_string(struct soap *soap, char *const *p) { soap_free_temp(soap); if (p) { if (soap_begin_send(soap) || soap_put_string(soap, p, "string", "") || soap_end_send(soap)) return soap->error; } return SOAP_OK; } SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap*, char **, const char*, const char*); inline int soap_read_string(struct soap *soap, char **p) { if (p) { if (soap_begin_recv(soap) || soap_get_string(soap, p, NULL, NULL) == NULL || soap_end_recv(soap)) return soap->error; } return SOAP_OK; } #endif #endif /* End of soapH.h */ <file_sep>/* soapC.cpp Generated by gSOAP 2.8.32 for soap.h gSOAP XML Web services tools Copyright (C) 2000-2016, <NAME>, Genivia Inc. All Rights Reserved. The soapcpp2 tool and its generated software are released under the GPL. This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia Inc., <EMAIL> -------------------------------------------------------------------------------- */ #if defined(__BORLANDC__) #pragma option push -w-8060 #pragma option push -w-8004 #endif #include "soapH.h" SOAP_SOURCE_STAMP("@(#) soapC.cpp ver 2.8.32 2016-09-01 08:27:08 GMT") #ifndef WITH_NOGLOBAL SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap) { soap->part = SOAP_IN_HEADER; soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", soap->header, NULL); soap->part = SOAP_END_HEADER; return soap->header == NULL; } SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap) { if (soap->version && soap->header) { soap->part = SOAP_IN_HEADER; if (soap_out_SOAP_ENV__Header(soap, "SOAP-ENV:Header", 0, soap->header, "")) return soap->error; soap->part = SOAP_END_HEADER; } return SOAP_OK; } SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap) { if (soap->version && soap->header) soap_serialize_SOAP_ENV__Header(soap, soap->header); } SOAP_FMAC3 void SOAP_FMAC4 soap_header(struct soap *soap) { if (soap->header == NULL) { if ((soap->header = soap_new_SOAP_ENV__Header(soap))) soap_default_SOAP_ENV__Header(soap, soap->header); } } SOAP_FMAC3 void SOAP_FMAC4 soap_fault(struct soap *soap) { if (soap->fault == NULL) { soap->fault = soap_new_SOAP_ENV__Fault(soap); if (soap->fault == NULL) return; soap_default_SOAP_ENV__Fault(soap, soap->fault); } if (soap->version == 2 && !soap->fault->SOAP_ENV__Code) { soap->fault->SOAP_ENV__Code = soap_new_SOAP_ENV__Code(soap); soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code); } if (soap->version == 2 && !soap->fault->SOAP_ENV__Reason) { soap->fault->SOAP_ENV__Reason = soap_new_SOAP_ENV__Reason(soap); soap_default_SOAP_ENV__Reason(soap, soap->fault->SOAP_ENV__Reason); } } SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap *soap) { soap_fault(soap); if (soap->fault) soap_serialize_SOAP_ENV__Fault(soap, soap->fault); } SOAP_FMAC3 int SOAP_FMAC4 soap_putfault(struct soap *soap) { if (soap->fault) return soap_put_SOAP_ENV__Fault(soap, soap->fault, "SOAP-ENV:Fault", ""); return SOAP_OK; } SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap) { return (soap->fault = soap_get_SOAP_ENV__Fault(soap, NULL, "SOAP-ENV:Fault", NULL)) == NULL; } SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap) { soap_fault(soap); if (soap->version == 2 && soap->fault->SOAP_ENV__Code) return (const char**)(void*)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Value; return (const char**)(void*)&soap->fault->faultcode; } SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap) { soap_fault(soap); if (soap->version == 2) { if (soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode == NULL) { soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode = soap_new_SOAP_ENV__Code(soap); soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode); } return (const char**)(void*)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value; } return (const char**)(void*)&soap->fault->faultcode; } SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultsubcode(struct soap *soap) { soap_fault(soap); if (soap->version == 2) { if (soap->fault->SOAP_ENV__Code && soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode) return soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value; return NULL; } return soap->fault->faultcode; } SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap) { soap_fault(soap); if (soap->version == 2) return (const char**)(void*)&soap->fault->SOAP_ENV__Reason->SOAP_ENV__Text; return (const char**)(void*)&soap->fault->faultstring; } SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap) { soap_fault(soap); if (soap->version == 2) { if (soap->fault->SOAP_ENV__Detail == NULL) { soap->fault->SOAP_ENV__Detail = soap_new_SOAP_ENV__Detail(soap); soap_default_SOAP_ENV__Detail(soap, soap->fault->SOAP_ENV__Detail); } return (const char**)(void*)&soap->fault->SOAP_ENV__Detail->__any; } if (soap->fault->detail == NULL) { soap->fault->detail = soap_new_SOAP_ENV__Detail(soap); soap_default_SOAP_ENV__Detail(soap, soap->fault->detail); } return (const char**)(void*)&soap->fault->detail->__any; } SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultdetail(struct soap *soap) { soap_fault(soap); if (soap->version == 2 && soap->fault->SOAP_ENV__Detail) return soap->fault->SOAP_ENV__Detail->__any; if (soap->fault->detail) return soap->fault->detail->__any; return NULL; } #endif #ifndef WITH_NOIDREF SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap *soap) { int t; if (soap->version == 1) { for (;;) { if (!soap_getelement(soap, &t)) if ((soap->error && soap->error != SOAP_TAG_MISMATCH) || soap_ignore_element(soap)) break; } } if (soap->error == SOAP_NO_TAG || soap->error == SOAP_EOF) soap->error = SOAP_OK; return soap->error; } #endif #ifdef __cplusplus extern "C" { #endif SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap *soap, int *type) { (void)type; if (soap_peek_element(soap)) return NULL; #ifndef WITH_NOIDREF if (!*soap->id || !(*type = soap_lookup_type(soap, soap->id))) *type = soap_lookup_type(soap, soap->href); switch (*type) { case SOAP_TYPE_byte: return soap_in_byte(soap, NULL, NULL, "xsd:byte"); case SOAP_TYPE_int: return soap_in_int(soap, NULL, NULL, "xsd:int"); case SOAP_TYPE_bool: return soap_in_bool(soap, NULL, NULL, "xsd:boolean"); case SOAP_TYPE_DataRep: return soap_in_DataRep(soap, NULL, NULL, "DataRep"); case SOAP_TYPE_DataArray: return soap_in_DataArray(soap, NULL, NULL, "DataArray"); case SOAP_TYPE_Data: return soap_in_Data(soap, NULL, NULL, "Data"); case SOAP_TYPE_std__string: return soap_in_std__string(soap, NULL, NULL, "xsd:string"); case SOAP_TYPE_ResponseBase: return soap_in_ResponseBase(soap, NULL, NULL, "ResponseBase"); case SOAP_TYPE_ns2__getData: return soap_in_ns2__getData(soap, NULL, NULL, "ns2:getData"); case SOAP_TYPE_ns2__getDataResponse: return soap_in_ns2__getDataResponse(soap, NULL, NULL, "ns2:getDataResponse"); case SOAP_TYPE_PointerToData: return soap_in_PointerToData(soap, NULL, NULL, "Data"); case SOAP_TYPE__QName: { char **s; s = soap_in__QName(soap, NULL, NULL, "xsd:QName"); return s ? *s : NULL; } case SOAP_TYPE_string: { char **s; s = soap_in_string(soap, NULL, NULL, "xsd:string"); return s ? *s : NULL; } default: #else *type = 0; #endif { const char *t = soap->type; if (!*t) t = soap->tag; if (!soap_match_tag(soap, t, "DataRep")) { *type = SOAP_TYPE_DataRep; return soap_in_DataRep(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "DataArray")) { *type = SOAP_TYPE_DataArray; return soap_in_DataArray(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "Data")) { *type = SOAP_TYPE_Data; return soap_in_Data(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "xsd:string")) { *type = SOAP_TYPE_std__string; return soap_in_std__string(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "ResponseBase")) { *type = SOAP_TYPE_ResponseBase; return soap_in_ResponseBase(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "xsd:byte")) { *type = SOAP_TYPE_byte; return soap_in_byte(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "xsd:int")) { *type = SOAP_TYPE_int; return soap_in_int(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "xsd:boolean")) { *type = SOAP_TYPE_bool; return soap_in_bool(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "ns2:getData")) { *type = SOAP_TYPE_ns2__getData; return soap_in_ns2__getData(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "ns2:getDataResponse")) { *type = SOAP_TYPE_ns2__getDataResponse; return soap_in_ns2__getDataResponse(soap, NULL, NULL, NULL); } if (!soap_match_tag(soap, t, "xsd:QName")) { char **s; *type = SOAP_TYPE__QName; s = soap_in__QName(soap, NULL, NULL, NULL); return s ? *s : NULL; } if (!soap_match_tag(soap, t, "xsd:string")) { char **s; *type = SOAP_TYPE_string; s = soap_in_string(soap, NULL, NULL, NULL); return s ? *s : NULL; } t = soap->tag; #ifndef WITH_NOIDREF } #endif } soap->error = SOAP_TAG_MISMATCH; return NULL; } #ifdef __cplusplus } #endif SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap *soap) { if (!soap_peek_element(soap)) { int t; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unexpected element '%s' in input (level = %u, %d)\n", soap->tag, soap->level, soap->body)); if (soap->mustUnderstand && !soap->other && !soap->fignore) return soap->error = SOAP_MUSTUNDERSTAND; if (((soap->mode & SOAP_XML_STRICT) && soap->part != SOAP_IN_HEADER) || !soap_match_tag(soap, soap->tag, "SOAP-ENV:")) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "REJECTING element '%s'\n", soap->tag)); return soap->error = SOAP_TAG_MISMATCH; } if (!*soap->id || !soap_getelement(soap, &t)) { soap->peeked = 0; if (soap->fignore) soap->error = soap->fignore(soap, soap->tag); else soap->error = SOAP_OK; DBGLOG(TEST, if (!soap->error) SOAP_MESSAGE(fdebug, "IGNORING element '%s'\n", soap->tag)); if (!soap->error && soap->body) { soap->level++; if (soap_ignore(soap) || soap_element_end_in(soap, NULL)) return soap->error; } } } return soap->error; } #ifndef WITH_NOIDREF SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap *soap) { int i; struct soap_plist *pp; if (soap->version == 1 && soap->encodingStyle && !(soap->mode & (SOAP_XML_TREE | SOAP_XML_GRAPH))) for (i = 0; i < SOAP_PTRHASH; i++) for (pp = soap->pht[i]; pp; pp = pp->next) if (pp->mark1 == 2 || pp->mark2 == 2) if (soap_putelement(soap, pp->ptr, SOAP_MULTIREFTAG, pp->id, pp->type)) return soap->error; return SOAP_OK; } #endif #ifdef __cplusplus extern "C" { #endif SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap *soap, const void *ptr, const char *tag, int id, int type) { (void)tag; switch (type) { case SOAP_TYPE_byte: return soap_out_byte(soap, tag, id, (const char *)ptr, "xsd:byte"); case SOAP_TYPE_int: return soap_out_int(soap, tag, id, (const int *)ptr, "xsd:int"); case SOAP_TYPE_bool: return soap_out_bool(soap, tag, id, (const bool *)ptr, "xsd:boolean"); case SOAP_TYPE_DataRep: return ((DataRep *)ptr)->soap_out(soap, tag, id, "DataRep"); case SOAP_TYPE_DataArray: return ((DataArray *)ptr)->soap_out(soap, tag, id, "DataArray"); case SOAP_TYPE_Data: return ((Data *)ptr)->soap_out(soap, tag, id, "Data"); case SOAP_TYPE_std__string: return soap_out_std__string(soap, tag, id, (const std::string *)ptr, "xsd:string"); case SOAP_TYPE_ResponseBase: return ((ResponseBase *)ptr)->soap_out(soap, tag, id, "ResponseBase"); case SOAP_TYPE_ns2__getData: return soap_out_ns2__getData(soap, tag, id, (const struct ns2__getData *)ptr, "ns2:getData"); case SOAP_TYPE_ns2__getDataResponse: return soap_out_ns2__getDataResponse(soap, tag, id, (const struct ns2__getDataResponse *)ptr, "ns2:getDataResponse"); case SOAP_TYPE_PointerToData: return soap_out_PointerToData(soap, tag, id, (Data *const*)ptr, "Data"); case SOAP_TYPE__QName: return soap_out_string(soap, tag, id, (char*const*)(void*)&ptr, "xsd:QName"); case SOAP_TYPE_string: return soap_out_string(soap, tag, id, (char*const*)(void*)&ptr, "xsd:string"); } return SOAP_OK; } #ifdef __cplusplus } #endif #ifndef WITH_NOIDREF #ifdef __cplusplus extern "C" { #endif SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap *soap, const void *ptr, int type) { (void)soap; (void)ptr; (void)type; /* appease -Wall -Werror */ switch (type) { case SOAP_TYPE_DataRep: ((DataRep *)ptr)->soap_serialize(soap); break; case SOAP_TYPE_DataArray: ((DataArray *)ptr)->soap_serialize(soap); break; case SOAP_TYPE_Data: ((Data *)ptr)->soap_serialize(soap); break; case SOAP_TYPE_std__string: soap_serialize_std__string(soap, (const std::string *)ptr); break; case SOAP_TYPE_ResponseBase: ((ResponseBase *)ptr)->soap_serialize(soap); break; case SOAP_TYPE_ns2__getData: soap_serialize_ns2__getData(soap, (const struct ns2__getData *)ptr); break; case SOAP_TYPE_ns2__getDataResponse: soap_serialize_ns2__getDataResponse(soap, (const struct ns2__getDataResponse *)ptr); break; case SOAP_TYPE_PointerToData: soap_serialize_PointerToData(soap, (Data *const*)ptr); break; case SOAP_TYPE__QName: soap_serialize_string(soap, (char*const*)(void*)&ptr); break; case SOAP_TYPE_string: soap_serialize_string(soap, (char*const*)(void*)&ptr); break; } } #ifdef __cplusplus } #endif #endif SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap *soap, int t, const char *type, const char *arrayType, size_t *n) { (void)type; switch (t) { case SOAP_TYPE_std__string: return (void*)soap_instantiate_std__string(soap, -1, type, arrayType, n); case SOAP_TYPE_ResponseBase: return (void*)soap_instantiate_ResponseBase(soap, -1, type, arrayType, n); case SOAP_TYPE_Data: return (void*)soap_instantiate_Data(soap, -1, type, arrayType, n); case SOAP_TYPE_DataArray: return (void*)soap_instantiate_DataArray(soap, -1, type, arrayType, n); case SOAP_TYPE_DataRep: return (void*)soap_instantiate_DataRep(soap, -1, type, arrayType, n); case SOAP_TYPE_ns2__getDataResponse: return (void*)soap_instantiate_ns2__getDataResponse(soap, -1, type, arrayType, n); case SOAP_TYPE_ns2__getData: return (void*)soap_instantiate_ns2__getData(soap, -1, type, arrayType, n); #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Header: return (void*)soap_instantiate_SOAP_ENV__Header(soap, -1, type, arrayType, n); #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Code: return (void*)soap_instantiate_SOAP_ENV__Code(soap, -1, type, arrayType, n); #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Detail: return (void*)soap_instantiate_SOAP_ENV__Detail(soap, -1, type, arrayType, n); #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Reason: return (void*)soap_instantiate_SOAP_ENV__Reason(soap, -1, type, arrayType, n); #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Fault: return (void*)soap_instantiate_SOAP_ENV__Fault(soap, -1, type, arrayType, n); #endif } return NULL; } SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist *p) { switch (p->type) { case SOAP_TYPE_std__string: if (p->size < 0) SOAP_DELETE(static_cast<std::string*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<std::string*>(p->ptr)); break; case SOAP_TYPE_ResponseBase: if (p->size < 0) SOAP_DELETE(static_cast<ResponseBase*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<ResponseBase*>(p->ptr)); break; case SOAP_TYPE_Data: if (p->size < 0) SOAP_DELETE(static_cast<Data*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<Data*>(p->ptr)); break; case SOAP_TYPE_DataArray: if (p->size < 0) SOAP_DELETE(static_cast<DataArray*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<DataArray*>(p->ptr)); break; case SOAP_TYPE_DataRep: if (p->size < 0) SOAP_DELETE(static_cast<DataRep*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<DataRep*>(p->ptr)); break; case SOAP_TYPE_ns2__getDataResponse: if (p->size < 0) SOAP_DELETE(static_cast<struct ns2__getDataResponse*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct ns2__getDataResponse*>(p->ptr)); break; case SOAP_TYPE_ns2__getData: if (p->size < 0) SOAP_DELETE(static_cast<struct ns2__getData*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct ns2__getData*>(p->ptr)); break; #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Header: if (p->size < 0) SOAP_DELETE(static_cast<struct SOAP_ENV__Header*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct SOAP_ENV__Header*>(p->ptr)); break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Code: if (p->size < 0) SOAP_DELETE(static_cast<struct SOAP_ENV__Code*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct SOAP_ENV__Code*>(p->ptr)); break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Detail: if (p->size < 0) SOAP_DELETE(static_cast<struct SOAP_ENV__Detail*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct SOAP_ENV__Detail*>(p->ptr)); break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Reason: if (p->size < 0) SOAP_DELETE(static_cast<struct SOAP_ENV__Reason*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct SOAP_ENV__Reason*>(p->ptr)); break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Fault: if (p->size < 0) SOAP_DELETE(static_cast<struct SOAP_ENV__Fault*>(p->ptr)); else SOAP_DELETE_ARRAY(static_cast<struct SOAP_ENV__Fault*>(p->ptr)); break; #endif default: return SOAP_ERR; } return SOAP_OK; } #ifdef WIN32 #pragma warning(push) // do not warn on switch w/o cases #pragma warning(disable:4065) #endif SOAP_FMAC3 int SOAP_FMAC4 soap_fbase(int t, int b) { do { switch (t) { case SOAP_TYPE_DataRep: t = SOAP_TYPE_ResponseBase; break; default: return 0; } } while (t != b); return 1; } #ifdef WIN32 #pragma warning(pop) #endif #ifndef WITH_NOIDREF #ifdef WIN32 #pragma warning(push) // do not warn on switch w/o cases #pragma warning(disable:4065) #endif SOAP_FMAC3 void SOAP_FMAC4 soap_finsert(struct soap *soap, int t, int tt, void *p, size_t index, const void *q, void **x) { (void)soap; (void)t; (void)p; (void)index; (void)q; (void)x; /* appease -Wall -Werror */ switch (tt) { case SOAP_TYPE_std__string: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy std::string type=%d location=%p object=%p\n", t, p, q)); *(std::string*)p = *(std::string*)q; break; case SOAP_TYPE_ResponseBase: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy ResponseBase type=%d location=%p object=%p\n", t, p, q)); *(ResponseBase*)p = *(ResponseBase*)q; break; case SOAP_TYPE_Data: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy Data type=%d location=%p object=%p\n", t, p, q)); *(Data*)p = *(Data*)q; break; case SOAP_TYPE_DataArray: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy DataArray type=%d location=%p object=%p\n", t, p, q)); *(DataArray*)p = *(DataArray*)q; break; case SOAP_TYPE_DataRep: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy DataRep type=%d location=%p object=%p\n", t, p, q)); *(DataRep*)p = *(DataRep*)q; break; case SOAP_TYPE_ns2__getDataResponse: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct ns2__getDataResponse type=%d location=%p object=%p\n", t, p, q)); *(struct ns2__getDataResponse*)p = *(struct ns2__getDataResponse*)q; break; case SOAP_TYPE_ns2__getData: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct ns2__getData type=%d location=%p object=%p\n", t, p, q)); *(struct ns2__getData*)p = *(struct ns2__getData*)q; break; #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Header: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct SOAP_ENV__Header type=%d location=%p object=%p\n", t, p, q)); *(struct SOAP_ENV__Header*)p = *(struct SOAP_ENV__Header*)q; break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Code: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct SOAP_ENV__Code type=%d location=%p object=%p\n", t, p, q)); *(struct SOAP_ENV__Code*)p = *(struct SOAP_ENV__Code*)q; break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Detail: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct SOAP_ENV__Detail type=%d location=%p object=%p\n", t, p, q)); *(struct SOAP_ENV__Detail*)p = *(struct SOAP_ENV__Detail*)q; break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Reason: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct SOAP_ENV__Reason type=%d location=%p object=%p\n", t, p, q)); *(struct SOAP_ENV__Reason*)p = *(struct SOAP_ENV__Reason*)q; break; #endif #ifndef WITH_NOGLOBAL case SOAP_TYPE_SOAP_ENV__Fault: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy struct SOAP_ENV__Fault type=%d location=%p object=%p\n", t, p, q)); *(struct SOAP_ENV__Fault*)p = *(struct SOAP_ENV__Fault*)q; break; #endif default: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not insert type = %d in %d\n", t, tt)); } } #ifdef WIN32 #pragma warning(pop) #endif #endif SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap *soap, char *a) { (void)soap; /* appease -Wall -Werror */ #ifdef SOAP_DEFAULT_byte *a = SOAP_DEFAULT_byte; #else *a = (char)0; #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap *soap, const char *tag, int id, const char *a, const char *type) { return soap_outbyte(soap, tag, id, a, type, SOAP_TYPE_byte); } SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap *soap, const char *tag, char *a, const char *type) { a = soap_inbyte(soap, tag, a, type, SOAP_TYPE_byte); return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap *soap, const char *a, const char *tag, const char *type) { if (soap_out_byte(soap, tag?tag:"byte", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap *soap, char *p, const char *tag, const char *type) { if ((p = soap_in_byte(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap *soap, int *a) { (void)soap; /* appease -Wall -Werror */ #ifdef SOAP_DEFAULT_int *a = SOAP_DEFAULT_int; #else *a = (int)0; #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap *soap, const char *tag, int id, const int *a, const char *type) { return soap_outint(soap, tag, id, a, type, SOAP_TYPE_int); } SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap *soap, const char *tag, int *a, const char *type) { a = soap_inint(soap, tag, a, type, SOAP_TYPE_int); return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap *soap, const int *a, const char *tag, const char *type) { if (soap_out_int(soap, tag?tag:"int", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap *soap, int *p, const char *tag, const char *type) { if ((p = soap_in_int(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default_bool(struct soap *soap, bool *a) { (void)soap; /* appease -Wall -Werror */ #ifdef SOAP_DEFAULT_bool *a = SOAP_DEFAULT_bool; #else *a = (bool)0; #endif } static const struct soap_code_map soap_codes_bool[] = { { (LONG64)false, "false" }, { (LONG64)true, "true" }, { 0, NULL } }; SOAP_FMAC3S const char* SOAP_FMAC4S soap_bool2s(struct soap *soap, bool n) { (void)soap; /* appease -Wall -Werror */ return soap_code_str(soap_codes_bool, n != 0); } SOAP_FMAC3 int SOAP_FMAC4 soap_out_bool(struct soap *soap, const char *tag, int id, const bool *a, const char *type) { if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_bool), type) || soap_send(soap, soap_bool2s(soap, *a))) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3S int SOAP_FMAC4S soap_s2bool(struct soap *soap, const char *s, bool *a) { const struct soap_code_map *map; if (!s) return soap->error; map = soap_code(soap_codes_bool, s); if (map) *a = (bool)(map->code != 0); else { long n; if (soap_s2long(soap, s, &n) || n < 0 || n > 1) return soap->error = SOAP_TYPE; *a = (bool)(n != 0); } return SOAP_OK; } SOAP_FMAC3 bool * SOAP_FMAC4 soap_in_bool(struct soap *soap, const char *tag, bool *a, const char *type) { if (soap_element_begin_in(soap, tag, 0, NULL)) return NULL; if (*soap->type && soap_match_tag(soap, soap->type, type) && soap_match_tag(soap, soap->type, ":boolean")) { soap->error = SOAP_TYPE; return NULL; } a = (bool *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_bool, sizeof(bool), NULL, NULL, NULL, NULL); if (!a) return NULL; if (soap->body && !*soap->href) { if (soap_s2bool(soap, soap_value(soap), a) || soap_element_end_in(soap, tag)) return NULL; } else { a = (bool *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_bool, SOAP_TYPE_bool, sizeof(bool), 0, NULL, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_bool(struct soap *soap, const bool *a, const char *tag, const char *type) { if (soap_out_bool(soap, tag?tag:"boolean", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 bool * SOAP_FMAC4 soap_get_bool(struct soap *soap, bool *p, const char *tag, const char *type) { if ((p = soap_in_bool(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } void DataRep::soap_default(struct soap *soap) { (void)soap; /* appease -Wall -Werror */ this->ResponseBase::soap_default(soap); soap_default_int(soap, &this->DataRep::quantity); this->DataRep::dataArray.DataArray::soap_default(soap); } void DataRep::soap_serialize(struct soap *soap) const { (void)soap; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF this->DataRep::dataArray.soap_serialize(soap); this->ResponseBase::soap_serialize(soap); #endif } int DataRep::soap_out(struct soap *soap, const char *tag, int id, const char *type) const { return soap_out_DataRep(soap, tag, id, this, type); } SOAP_FMAC3 int SOAP_FMAC4 soap_out_DataRep(struct soap *soap, const char *tag, int id, const DataRep *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_DataRep), "DataRep")) return soap->error; if (soap_out_bool(soap, "status", -1, &a->ResponseBase::status, "")) return soap->error; if (soap_out_std__string(soap, "message", -1, &a->ResponseBase::message, "")) return soap->error; if (soap_out_std__string(soap, "dateTime", -1, &a->ResponseBase::dateTime, "")) return soap->error; if (soap_out_int(soap, "quantity", -1, &a->DataRep::quantity, "")) return soap->error; if ((a->DataRep::dataArray).soap_out(soap, "dataArray", -1, "")) return soap->error; return soap_element_end_out(soap, tag); } void *DataRep::soap_in(struct soap *soap, const char *tag, const char *type) { return soap_in_DataRep(soap, tag, this, type); } SOAP_FMAC3 DataRep * SOAP_FMAC4 soap_in_DataRep(struct soap *soap, const char *tag, DataRep *a, const char *type) { (void)tag; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 0, NULL)) return NULL; a = (DataRep *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_DataRep, sizeof(DataRep), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; if (soap->alloced && soap->alloced != SOAP_TYPE_DataRep) { soap_revert(soap); *soap->id = '\0'; return (DataRep *)a->soap_in(soap, tag, type); } if (soap->alloced) a->soap_default(soap); size_t soap_flag_status2 = 1; size_t soap_flag_message2 = 1; size_t soap_flag_dateTime2 = 1; size_t soap_flag_quantity1 = 1; size_t soap_flag_dataArray1 = 1; if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_status2 && soap->error == SOAP_TAG_MISMATCH) if (soap_in_bool(soap, "status", &a->ResponseBase::status, "xsd:boolean")) { soap_flag_status2--; continue; } if (soap_flag_message2 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "message", &a->ResponseBase::message, "xsd:string")) { soap_flag_message2--; continue; } if (soap_flag_dateTime2 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "dateTime", &a->ResponseBase::dateTime, "xsd:string")) { soap_flag_dateTime2--; continue; } if (soap_flag_quantity1 && soap->error == SOAP_TAG_MISMATCH) if (soap_in_int(soap, "quantity", &a->DataRep::quantity, "xsd:int")) { soap_flag_quantity1--; continue; } if (soap_flag_dataArray1 && soap->error == SOAP_TAG_MISMATCH) if ((a->DataRep::dataArray).soap_in(soap, "dataArray", "DataArray")) { soap_flag_dataArray1--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; if ((soap->mode & SOAP_XML_STRICT) && (soap_flag_status2 > 0 || soap_flag_message2 > 0 || soap_flag_dateTime2 > 0 || soap_flag_quantity1 > 0 || soap_flag_dataArray1 > 0)) { soap->error = SOAP_OCCURS; return NULL; } } else if ((soap->mode & SOAP_XML_STRICT) && !*soap->href) { soap->error = SOAP_OCCURS; return NULL; } else { a = (DataRep *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_DataRep, SOAP_TYPE_DataRep, sizeof(DataRep), 0, soap_finsert, soap_fbase); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 DataRep * SOAP_FMAC2 soap_instantiate_DataRep(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_DataRep(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ DataRep *p; size_t k = sizeof(DataRep); if (n < 0) { p = SOAP_NEW(DataRep); } else { p = SOAP_NEW_ARRAY(DataRep, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated DataRep location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_DataRep, n, soap_fdelete); if (size) *size = k; return p; } int DataRep::soap_put(struct soap *soap, const char *tag, const char *type) const { if (this->soap_out(soap, tag?tag:"DataRep", -2, type)) return soap->error; return soap_putindependent(soap); } void *DataRep::soap_get(struct soap *soap, const char *tag, const char *type) { return soap_get_DataRep(soap, this, tag, type); } SOAP_FMAC3 DataRep * SOAP_FMAC4 soap_get_DataRep(struct soap *soap, DataRep *p, const char *tag, const char *type) { if ((p = soap_in_DataRep(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } void DataArray::soap_default(struct soap *soap) { (void)soap; /* appease -Wall -Werror */ this->DataArray::__size = 0; this->DataArray::data = NULL; } void DataArray::soap_serialize(struct soap *soap) const { (void)soap; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF if (this->DataArray::data) { int i; for (i = 0; i < (int)this->DataArray::__size; i++) { soap_embedded(soap, this->DataArray::data + i, SOAP_TYPE_Data); this->DataArray::data[i].soap_serialize(soap); } } #endif } int DataArray::soap_out(struct soap *soap, const char *tag, int id, const char *type) const { return soap_out_DataArray(soap, tag, id, this, type); } SOAP_FMAC3 int SOAP_FMAC4 soap_out_DataArray(struct soap *soap, const char *tag, int id, const DataArray *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_DataArray), type)) return soap->error; if (a->DataArray::data) { int i; for (i = 0; i < (int)a->DataArray::__size; i++) if (a->DataArray::data[i].soap_out(soap, "data", -1, "")) return soap->error; } return soap_element_end_out(soap, tag); } void *DataArray::soap_in(struct soap *soap, const char *tag, const char *type) { return soap_in_DataArray(soap, tag, this, type); } SOAP_FMAC3 DataArray * SOAP_FMAC4 soap_in_DataArray(struct soap *soap, const char *tag, DataArray *a, const char *type) { (void)tag; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 0, NULL)) return NULL; a = (DataArray *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_DataArray, sizeof(DataArray), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; if (soap->alloced && soap->alloced != SOAP_TYPE_DataArray) { soap_revert(soap); *soap->id = '\0'; return (DataArray *)a->soap_in(soap, tag, type); } if (soap->alloced) a->soap_default(soap); struct soap_blist *soap_blist_data1 = NULL; if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap->error == SOAP_TAG_MISMATCH && !soap_element_begin_in(soap, "data", 1, NULL)) { if (a->DataArray::data == NULL) { if (soap_blist_data1 == NULL) soap_blist_data1 = soap_new_block(soap); a->DataArray::data = soap_block<Data>::push(soap, soap_blist_data1); if (a->DataArray::data == NULL) return NULL; a->DataArray::data->soap_default(soap); } soap_revert(soap); if (soap_in_Data(soap, "data", a->DataArray::data, "Data")) { a->DataArray::__size++; a->DataArray::data = NULL; continue; } } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (a->DataArray::data) soap_block<Data>::pop(soap, soap_blist_data1); if (a->DataArray::__size) { a->DataArray::data = soap_new_Data(soap, a->DataArray::__size); if (!a->DataArray::data) return NULL; soap_block<Data>::save(soap, soap_blist_data1, a->DataArray::data); } else { a->DataArray::data = NULL; if (soap_blist_data1) soap_block<Data>::end(soap, soap_blist_data1); } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (DataArray *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_DataArray, SOAP_TYPE_DataArray, sizeof(DataArray), 0, soap_finsert, soap_fbase); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 DataArray * SOAP_FMAC2 soap_instantiate_DataArray(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_DataArray(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ DataArray *p; size_t k = sizeof(DataArray); if (n < 0) { p = SOAP_NEW(DataArray); } else { p = SOAP_NEW_ARRAY(DataArray, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated DataArray location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_DataArray, n, soap_fdelete); if (size) *size = k; return p; } int DataArray::soap_put(struct soap *soap, const char *tag, const char *type) const { if (this->soap_out(soap, tag?tag:"DataArray", -2, type)) return soap->error; return soap_putindependent(soap); } void *DataArray::soap_get(struct soap *soap, const char *tag, const char *type) { return soap_get_DataArray(soap, this, tag, type); } SOAP_FMAC3 DataArray * SOAP_FMAC4 soap_get_DataArray(struct soap *soap, DataArray *p, const char *tag, const char *type) { if ((p = soap_in_DataArray(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } void Data::soap_default(struct soap *soap) { (void)soap; /* appease -Wall -Werror */ soap_default_std__string(soap, &this->Data::dateTime); soap_default_std__string(soap, &this->Data::content); } void Data::soap_serialize(struct soap *soap) const { (void)soap; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize_std__string(soap, &this->Data::dateTime); soap_serialize_std__string(soap, &this->Data::content); #endif } int Data::soap_out(struct soap *soap, const char *tag, int id, const char *type) const { return soap_out_Data(soap, tag, id, this, type); } SOAP_FMAC3 int SOAP_FMAC4 soap_out_Data(struct soap *soap, const char *tag, int id, const Data *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_Data), type)) return soap->error; if (soap_out_std__string(soap, "dateTime", -1, &a->Data::dateTime, "")) return soap->error; if (soap_out_std__string(soap, "content", -1, &a->Data::content, "")) return soap->error; return soap_element_end_out(soap, tag); } void *Data::soap_in(struct soap *soap, const char *tag, const char *type) { return soap_in_Data(soap, tag, this, type); } SOAP_FMAC3 Data * SOAP_FMAC4 soap_in_Data(struct soap *soap, const char *tag, Data *a, const char *type) { (void)tag; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 0, NULL)) return NULL; a = (Data *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_Data, sizeof(Data), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; if (soap->alloced && soap->alloced != SOAP_TYPE_Data) { soap_revert(soap); *soap->id = '\0'; return (Data *)a->soap_in(soap, tag, type); } if (soap->alloced) a->soap_default(soap); size_t soap_flag_dateTime1 = 1; size_t soap_flag_content1 = 1; if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_dateTime1 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "dateTime", &a->Data::dateTime, "xsd:string")) { soap_flag_dateTime1--; continue; } if (soap_flag_content1 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "content", &a->Data::content, "xsd:string")) { soap_flag_content1--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; if ((soap->mode & SOAP_XML_STRICT) && (soap_flag_dateTime1 > 0 || soap_flag_content1 > 0)) { soap->error = SOAP_OCCURS; return NULL; } } else if ((soap->mode & SOAP_XML_STRICT) && !*soap->href) { soap->error = SOAP_OCCURS; return NULL; } else { a = (Data *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_Data, SOAP_TYPE_Data, sizeof(Data), 0, soap_finsert, soap_fbase); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 Data * SOAP_FMAC2 soap_instantiate_Data(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_Data(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ Data *p; size_t k = sizeof(Data); if (n < 0) { p = SOAP_NEW(Data); } else { p = SOAP_NEW_ARRAY(Data, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated Data location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_Data, n, soap_fdelete); if (size) *size = k; return p; } int Data::soap_put(struct soap *soap, const char *tag, const char *type) const { if (this->soap_out(soap, tag?tag:"Data", -2, type)) return soap->error; return soap_putindependent(soap); } void *Data::soap_get(struct soap *soap, const char *tag, const char *type) { return soap_get_Data(soap, this, tag, type); } SOAP_FMAC3 Data * SOAP_FMAC4 soap_get_Data(struct soap *soap, Data *p, const char *tag, const char *type) { if ((p = soap_in_Data(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default_std__string(struct soap *soap, std::string *p) { (void)soap; /* appease -Wall -Werror */ p->erase(); } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_std__string(struct soap *soap, const std::string *a) { (void)soap; (void)a; /* appease -Wall -Werror */ } SOAP_FMAC3 int SOAP_FMAC4 soap_out_std__string(struct soap *soap, const char *tag, int id, const std::string *s, const char *type) { if ((soap->mode & SOAP_C_NILSTRING) && s->empty()) return soap_element_null(soap, tag, id, type); if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, s, SOAP_TYPE_std__string), type) || soap_string_out(soap, s->c_str(), 0) || soap_element_end_out(soap, tag)) return soap->error; return SOAP_OK; } SOAP_FMAC3 std::string * SOAP_FMAC4 soap_in_std__string(struct soap *soap, const char *tag, std::string *s, const char *type) { (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 1, NULL)) return NULL; if (!s) s = soap_new_std__string(soap, -1); if (soap->null) if (s) s->erase(); if (soap->body && !*soap->href) { char *t; s = (std::string*)soap_id_enter(soap, soap->id, s, SOAP_TYPE_std__string, sizeof(std::string), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (s) { if (!(t = soap_string_in(soap, 1, 0, -1, NULL))) return NULL; s->assign(t); } } else s = (std::string*)soap_id_forward(soap, soap->href, soap_id_enter(soap, soap->id, s, SOAP_TYPE_std__string, sizeof(std::string), soap->type, soap->arrayType, soap_instantiate, soap_fbase), 0, SOAP_TYPE_std__string, SOAP_TYPE_std__string, sizeof(std::string), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; return s; } SOAP_FMAC1 std::string * SOAP_FMAC2 soap_instantiate_std__string(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_std__string(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ std::string *p; size_t k = sizeof(std::string); if (n < 0) { p = SOAP_NEW(std::string); } else { p = SOAP_NEW_ARRAY(std::string, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated std::string location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_std__string, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_std__string(struct soap *soap, const std::string *a, const char *tag, const char *type) { if (soap_out_std__string(soap, tag?tag:"string", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 std::string * SOAP_FMAC4 soap_get_std__string(struct soap *soap, std::string *p, const char *tag, const char *type) { if ((p = soap_in_std__string(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } void ResponseBase::soap_default(struct soap *soap) { (void)soap; /* appease -Wall -Werror */ soap_default_bool(soap, &this->ResponseBase::status); soap_default_std__string(soap, &this->ResponseBase::message); soap_default_std__string(soap, &this->ResponseBase::dateTime); } void ResponseBase::soap_serialize(struct soap *soap) const { (void)soap; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize_std__string(soap, &this->ResponseBase::message); soap_serialize_std__string(soap, &this->ResponseBase::dateTime); #endif } int ResponseBase::soap_out(struct soap *soap, const char *tag, int id, const char *type) const { return soap_out_ResponseBase(soap, tag, id, this, type); } SOAP_FMAC3 int SOAP_FMAC4 soap_out_ResponseBase(struct soap *soap, const char *tag, int id, const ResponseBase *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ResponseBase), type)) return soap->error; if (soap_out_bool(soap, "status", -1, &a->ResponseBase::status, "")) return soap->error; if (soap_out_std__string(soap, "message", -1, &a->ResponseBase::message, "")) return soap->error; if (soap_out_std__string(soap, "dateTime", -1, &a->ResponseBase::dateTime, "")) return soap->error; return soap_element_end_out(soap, tag); } void *ResponseBase::soap_in(struct soap *soap, const char *tag, const char *type) { return soap_in_ResponseBase(soap, tag, this, type); } SOAP_FMAC3 ResponseBase * SOAP_FMAC4 soap_in_ResponseBase(struct soap *soap, const char *tag, ResponseBase *a, const char *type) { (void)tag; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 0, NULL)) return NULL; a = (ResponseBase *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ResponseBase, sizeof(ResponseBase), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; if (soap->alloced && soap->alloced != SOAP_TYPE_ResponseBase) { soap_revert(soap); *soap->id = '\0'; return (ResponseBase *)a->soap_in(soap, tag, type); } if (soap->alloced) a->soap_default(soap); size_t soap_flag_status1 = 1; size_t soap_flag_message1 = 1; size_t soap_flag_dateTime1 = 1; if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_status1 && soap->error == SOAP_TAG_MISMATCH) if (soap_in_bool(soap, "status", &a->ResponseBase::status, "xsd:boolean")) { soap_flag_status1--; continue; } if (soap_flag_message1 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "message", &a->ResponseBase::message, "xsd:string")) { soap_flag_message1--; continue; } if (soap_flag_dateTime1 && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "dateTime", &a->ResponseBase::dateTime, "xsd:string")) { soap_flag_dateTime1--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; if ((soap->mode & SOAP_XML_STRICT) && (soap_flag_status1 > 0 || soap_flag_message1 > 0 || soap_flag_dateTime1 > 0)) { soap->error = SOAP_OCCURS; return NULL; } } else if ((soap->mode & SOAP_XML_STRICT) && !*soap->href) { soap->error = SOAP_OCCURS; return NULL; } else { a = (ResponseBase *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ResponseBase, SOAP_TYPE_ResponseBase, sizeof(ResponseBase), 0, soap_finsert, soap_fbase); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 ResponseBase * SOAP_FMAC2 soap_instantiate_ResponseBase(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ResponseBase(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ if (soap && type && !soap_match_tag(soap, type, "DataRep")) return soap_instantiate_DataRep(soap, n, NULL, NULL, size); ResponseBase *p; size_t k = sizeof(ResponseBase); if (n < 0) { p = SOAP_NEW(ResponseBase); } else { p = SOAP_NEW_ARRAY(ResponseBase, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated ResponseBase location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_ResponseBase, n, soap_fdelete); if (size) *size = k; return p; } int ResponseBase::soap_put(struct soap *soap, const char *tag, const char *type) const { if (this->soap_out(soap, tag?tag:"ResponseBase", -2, type)) return soap->error; return soap_putindependent(soap); } void *ResponseBase::soap_get(struct soap *soap, const char *tag, const char *type) { return soap_get_ResponseBase(soap, this, tag, type); } SOAP_FMAC3 ResponseBase * SOAP_FMAC4 soap_get_ResponseBase(struct soap *soap, ResponseBase *p, const char *tag, const char *type) { if ((p = soap_in_ResponseBase(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *a) { (void)soap; (void)a; /* appease -Wall -Werror */ soap_default__QName(soap, &a->faultcode); soap_default_string(soap, &a->faultstring); soap_default_string(soap, &a->faultactor); a->detail = NULL; a->SOAP_ENV__Code = NULL; a->SOAP_ENV__Reason = NULL; soap_default_string(soap, &a->SOAP_ENV__Node); soap_default_string(soap, &a->SOAP_ENV__Role); a->SOAP_ENV__Detail = NULL; } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize__QName(soap, (char*const*)&a->faultcode); soap_serialize_string(soap, (char*const*)&a->faultstring); soap_serialize_string(soap, (char*const*)&a->faultactor); soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->detail); soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Code); soap_serialize_PointerToSOAP_ENV__Reason(soap, &a->SOAP_ENV__Reason); soap_serialize_string(soap, (char*const*)&a->SOAP_ENV__Node); soap_serialize_string(soap, (char*const*)&a->SOAP_ENV__Role); soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->SOAP_ENV__Detail); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Fault *a, const char *type) { const char *soap_tmp_faultcode = soap_QName2s(soap, a->faultcode); (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Fault), type)) return soap->error; if (soap_out__QName(soap, "faultcode", -1, (char*const*)(void*)&soap_tmp_faultcode, "")) return soap->error; if (soap_out_string(soap, "faultstring", -1, (char*const*)&a->faultstring, "")) return soap->error; if (soap_out_string(soap, "faultactor", -1, (char*const*)&a->faultactor, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Detail(soap, "detail", -1, &a->detail, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", -1, &a->SOAP_ENV__Code, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", -1, &a->SOAP_ENV__Reason, "")) return soap->error; if (soap_out_string(soap, "SOAP-ENV:Node", -1, (char*const*)&a->SOAP_ENV__Node, "")) return soap->error; if (soap_out_string(soap, "SOAP-ENV:Role", -1, (char*const*)&a->SOAP_ENV__Role, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", -1, &a->SOAP_ENV__Detail, "")) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap *soap, const char *tag, struct SOAP_ENV__Fault *a, const char *type) { size_t soap_flag_faultcode = 1; size_t soap_flag_faultstring = 1; size_t soap_flag_faultactor = 1; size_t soap_flag_detail = 1; size_t soap_flag_SOAP_ENV__Code = 1; size_t soap_flag_SOAP_ENV__Reason = 1; size_t soap_flag_SOAP_ENV__Node = 1; size_t soap_flag_SOAP_ENV__Role = 1; size_t soap_flag_SOAP_ENV__Detail = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct SOAP_ENV__Fault *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Fault, sizeof(struct SOAP_ENV__Fault), NULL, NULL, NULL, NULL); if (!a) return NULL; soap_default_SOAP_ENV__Fault(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_faultcode && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in__QName(soap, "faultcode", (char**)&a->faultcode, "xsd:QName")) { soap_flag_faultcode--; continue; } if (soap_flag_faultstring && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_string(soap, "faultstring", (char**)&a->faultstring, "xsd:string")) { soap_flag_faultstring--; continue; } if (soap_flag_faultactor && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_string(soap, "faultactor", (char**)&a->faultactor, "xsd:string")) { soap_flag_faultactor--; continue; } if (soap_flag_detail && soap->error == SOAP_TAG_MISMATCH) if (soap_in_PointerToSOAP_ENV__Detail(soap, "detail", &a->detail, "")) { soap_flag_detail--; continue; } if (soap_flag_SOAP_ENV__Code && soap->error == SOAP_TAG_MISMATCH) if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", &a->SOAP_ENV__Code, "")) { soap_flag_SOAP_ENV__Code--; continue; } if (soap_flag_SOAP_ENV__Reason && soap->error == SOAP_TAG_MISMATCH) if (soap_in_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", &a->SOAP_ENV__Reason, "")) { soap_flag_SOAP_ENV__Reason--; continue; } if (soap_flag_SOAP_ENV__Node && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_string(soap, "SOAP-ENV:Node", (char**)&a->SOAP_ENV__Node, "xsd:string")) { soap_flag_SOAP_ENV__Node--; continue; } if (soap_flag_SOAP_ENV__Role && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_string(soap, "SOAP-ENV:Role", (char**)&a->SOAP_ENV__Role, "xsd:string")) { soap_flag_SOAP_ENV__Role--; continue; } if (soap_flag_SOAP_ENV__Detail && soap->error == SOAP_TAG_MISMATCH) if (soap_in_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", &a->SOAP_ENV__Detail, "")) { soap_flag_SOAP_ENV__Detail--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (struct SOAP_ENV__Fault *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Fault, SOAP_TYPE_SOAP_ENV__Fault, sizeof(struct SOAP_ENV__Fault), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Fault(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct SOAP_ENV__Fault *p; size_t k = sizeof(struct SOAP_ENV__Fault); if (n < 0) { p = SOAP_NEW(struct SOAP_ENV__Fault); } else { p = SOAP_NEW_ARRAY(struct SOAP_ENV__Fault, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct SOAP_ENV__Fault location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_SOAP_ENV__Fault, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a, const char *tag, const char *type) { if (soap_out_SOAP_ENV__Fault(soap, tag?tag:"SOAP-ENV:Fault", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p, const char *tag, const char *type) { if ((p = soap_in_SOAP_ENV__Fault(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *a) { (void)soap; (void)a; /* appease -Wall -Werror */ soap_default_string(soap, &a->SOAP_ENV__Text); } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize_string(soap, (char*const*)&a->SOAP_ENV__Text); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Reason *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Reason), type)) return soap->error; if (soap->lang) soap_set_attr(soap, "xml:lang", soap->lang, 1); if (soap_out_string(soap, "SOAP-ENV:Text", -1, (char*const*)&a->SOAP_ENV__Text, "")) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason *a, const char *type) { size_t soap_flag_SOAP_ENV__Text = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct SOAP_ENV__Reason *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), NULL, NULL, NULL, NULL); if (!a) return NULL; soap_default_SOAP_ENV__Reason(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_SOAP_ENV__Text && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_string(soap, "SOAP-ENV:Text", (char**)&a->SOAP_ENV__Text, "xsd:string")) { soap_flag_SOAP_ENV__Text--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (struct SOAP_ENV__Reason *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Reason, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reason(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Reason(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct SOAP_ENV__Reason *p; size_t k = sizeof(struct SOAP_ENV__Reason); if (n < 0) { p = SOAP_NEW(struct SOAP_ENV__Reason); } else { p = SOAP_NEW_ARRAY(struct SOAP_ENV__Reason, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct SOAP_ENV__Reason location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_SOAP_ENV__Reason, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a, const char *tag, const char *type) { if (soap_out_SOAP_ENV__Reason(soap, tag?tag:"SOAP-ENV:Reason", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p, const char *tag, const char *type) { if ((p = soap_in_SOAP_ENV__Reason(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *a) { (void)soap; (void)a; /* appease -Wall -Werror */ a->__any = NULL; a->__type = 0; a->fault = NULL; } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_markelement(soap, a->fault, a->__type); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Detail *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Detail), type)) return soap->error; soap_outliteral(soap, "-any", (char*const*)&a->__any, NULL); if (soap_putelement(soap, a->fault, "fault", -1, a->__type)) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail *a, const char *type) { size_t soap_flag___any = 1; size_t soap_flag_fault = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct SOAP_ENV__Detail *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), NULL, NULL, NULL, NULL); if (!a) return NULL; soap_default_SOAP_ENV__Detail(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_fault && soap->error == SOAP_TAG_MISMATCH) if ((a->fault = soap_getelement(soap, &a->__type))) { soap_flag_fault = 0; continue; } if (soap_flag___any && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_inliteral(soap, "-any", (char**)&a->__any)) { soap_flag___any--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (struct SOAP_ENV__Detail *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Detail, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detail(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Detail(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct SOAP_ENV__Detail *p; size_t k = sizeof(struct SOAP_ENV__Detail); if (n < 0) { p = SOAP_NEW(struct SOAP_ENV__Detail); } else { p = SOAP_NEW_ARRAY(struct SOAP_ENV__Detail, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct SOAP_ENV__Detail location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_SOAP_ENV__Detail, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a, const char *tag, const char *type) { if (soap_out_SOAP_ENV__Detail(soap, tag?tag:"SOAP-ENV:Detail", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p, const char *tag, const char *type) { if ((p = soap_in_SOAP_ENV__Detail(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *a) { (void)soap; (void)a; /* appease -Wall -Werror */ soap_default__QName(soap, &a->SOAP_ENV__Value); a->SOAP_ENV__Subcode = NULL; } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize__QName(soap, (char*const*)&a->SOAP_ENV__Value); soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Subcode); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Code *a, const char *type) { const char *soap_tmp_SOAP_ENV__Value = soap_QName2s(soap, a->SOAP_ENV__Value); (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Code), type)) return soap->error; if (soap_out__QName(soap, "SOAP-ENV:Value", -1, (char*const*)(void*)&soap_tmp_SOAP_ENV__Value, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", -1, &a->SOAP_ENV__Subcode, "")) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code *a, const char *type) { size_t soap_flag_SOAP_ENV__Value = 1; size_t soap_flag_SOAP_ENV__Subcode = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct SOAP_ENV__Code *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), NULL, NULL, NULL, NULL); if (!a) return NULL; soap_default_SOAP_ENV__Code(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_SOAP_ENV__Value && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in__QName(soap, "SOAP-ENV:Value", (char**)&a->SOAP_ENV__Value, "xsd:QName")) { soap_flag_SOAP_ENV__Value--; continue; } if (soap_flag_SOAP_ENV__Subcode && soap->error == SOAP_TAG_MISMATCH) if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", &a->SOAP_ENV__Subcode, "")) { soap_flag_SOAP_ENV__Subcode--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (struct SOAP_ENV__Code *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Code, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Code(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct SOAP_ENV__Code *p; size_t k = sizeof(struct SOAP_ENV__Code); if (n < 0) { p = SOAP_NEW(struct SOAP_ENV__Code); } else { p = SOAP_NEW_ARRAY(struct SOAP_ENV__Code, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct SOAP_ENV__Code location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_SOAP_ENV__Code, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a, const char *tag, const char *type) { if (soap_out_SOAP_ENV__Code(soap, tag?tag:"SOAP-ENV:Code", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p, const char *tag, const char *type) { if ((p = soap_in_SOAP_ENV__Code(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *a) { (void)soap; (void)a; /* appease -Wall -Werror */ } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Header *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Header), type)) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap *soap, const char *tag, struct SOAP_ENV__Header *a, const char *type) { if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct SOAP_ENV__Header *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Header, sizeof(struct SOAP_ENV__Header), NULL, NULL, NULL, NULL); if (!a) return NULL; soap_default_SOAP_ENV__Header(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; } else { a = (struct SOAP_ENV__Header *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Header, SOAP_TYPE_SOAP_ENV__Header, sizeof(struct SOAP_ENV__Header), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Header(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Header(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct SOAP_ENV__Header *p; size_t k = sizeof(struct SOAP_ENV__Header); if (n < 0) { p = SOAP_NEW(struct SOAP_ENV__Header); } else { p = SOAP_NEW_ARRAY(struct SOAP_ENV__Header, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct SOAP_ENV__Header location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_SOAP_ENV__Header, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a, const char *tag, const char *type) { if (soap_out_SOAP_ENV__Header(soap, tag?tag:"SOAP-ENV:Header", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p, const char *tag, const char *type) { if ((p = soap_in_SOAP_ENV__Header(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns2__getData(struct soap *soap, struct ns2__getData *a) { (void)soap; (void)a; /* appease -Wall -Werror */ soap_default_std__string(soap, &a->name); } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns2__getData(struct soap *soap, const struct ns2__getData *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_serialize_std__string(soap, &a->name); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns2__getData(struct soap *soap, const char *tag, int id, const struct ns2__getData *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns2__getData), type)) return soap->error; if (soap_out_std__string(soap, "name", -1, &a->name, "")) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct ns2__getData * SOAP_FMAC4 soap_in_ns2__getData(struct soap *soap, const char *tag, struct ns2__getData *a, const char *type) { size_t soap_flag_name = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct ns2__getData *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns2__getData, sizeof(struct ns2__getData), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; soap_default_ns2__getData(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_name && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) if (soap_in_std__string(soap, "name", &a->name, "xsd:string")) { soap_flag_name--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; if ((soap->mode & SOAP_XML_STRICT) && (soap_flag_name > 0)) { soap->error = SOAP_OCCURS; return NULL; } } else if ((soap->mode & SOAP_XML_STRICT) && !*soap->href) { soap->error = SOAP_OCCURS; return NULL; } else { a = (struct ns2__getData *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns2__getData, SOAP_TYPE_ns2__getData, sizeof(struct ns2__getData), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct ns2__getData * SOAP_FMAC2 soap_instantiate_ns2__getData(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns2__getData(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct ns2__getData *p; size_t k = sizeof(struct ns2__getData); if (n < 0) { p = SOAP_NEW(struct ns2__getData); } else { p = SOAP_NEW_ARRAY(struct ns2__getData, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct ns2__getData location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_ns2__getData, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns2__getData(struct soap *soap, const struct ns2__getData *a, const char *tag, const char *type) { if (soap_out_ns2__getData(soap, tag?tag:"ns2:getData", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct ns2__getData * SOAP_FMAC4 soap_get_ns2__getData(struct soap *soap, struct ns2__getData *p, const char *tag, const char *type) { if ((p = soap_in_ns2__getData(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns2__getDataResponse(struct soap *soap, struct ns2__getDataResponse *a) { (void)soap; (void)a; /* appease -Wall -Werror */ a->result.DataRep::soap_default(soap); } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns2__getDataResponse(struct soap *soap, const struct ns2__getDataResponse *a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF a->result.soap_serialize(soap); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns2__getDataResponse(struct soap *soap, const char *tag, int id, const struct ns2__getDataResponse *a, const char *type) { (void)soap; (void)tag; (void)id; (void)a; (void)type; /* appease -Wall -Werror */ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns2__getDataResponse), type)) return soap->error; if (a->result.soap_out(soap, "result", -1, "")) return soap->error; return soap_element_end_out(soap, tag); } SOAP_FMAC3 struct ns2__getDataResponse * SOAP_FMAC4 soap_in_ns2__getDataResponse(struct soap *soap, const char *tag, struct ns2__getDataResponse *a, const char *type) { size_t soap_flag_result = 1; if (soap_element_begin_in(soap, tag, 0, type)) return NULL; a = (struct ns2__getDataResponse *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns2__getDataResponse, sizeof(struct ns2__getDataResponse), soap->type, soap->arrayType, soap_instantiate, soap_fbase); if (!a) return NULL; soap_default_ns2__getDataResponse(soap, a); if (soap->body && !*soap->href) { for (;;) { soap->error = SOAP_TAG_MISMATCH; if (soap_flag_result && soap->error == SOAP_TAG_MISMATCH) if (a->result.soap_in(soap, "result", "DataRep")) { soap_flag_result--; continue; } if (soap->error == SOAP_TAG_MISMATCH) soap->error = soap_ignore_element(soap); if (soap->error == SOAP_NO_TAG) break; if (soap->error) return NULL; } if (soap_element_end_in(soap, tag)) return NULL; if ((soap->mode & SOAP_XML_STRICT) && (soap_flag_result > 0)) { soap->error = SOAP_OCCURS; return NULL; } } else if ((soap->mode & SOAP_XML_STRICT) && !*soap->href) { soap->error = SOAP_OCCURS; return NULL; } else { a = (struct ns2__getDataResponse *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns2__getDataResponse, SOAP_TYPE_ns2__getDataResponse, sizeof(struct ns2__getDataResponse), 0, soap_finsert, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC1 struct ns2__getDataResponse * SOAP_FMAC2 soap_instantiate_ns2__getDataResponse(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns2__getDataResponse(%p, %d, %s, %s)\n", soap, n, type?type:"", arrayType?arrayType:"")); (void)type; (void)arrayType; /* appease -Wall -Werror */ struct ns2__getDataResponse *p; size_t k = sizeof(struct ns2__getDataResponse); if (n < 0) { p = SOAP_NEW(struct ns2__getDataResponse); } else { p = SOAP_NEW_ARRAY(struct ns2__getDataResponse, n); k *= n; } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated struct ns2__getDataResponse location=%p n=%d\n", p, n)); soap_link(soap, p, SOAP_TYPE_ns2__getDataResponse, n, soap_fdelete); if (size) *size = k; return p; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns2__getDataResponse(struct soap *soap, const struct ns2__getDataResponse *a, const char *tag, const char *type) { if (soap_out_ns2__getDataResponse(soap, tag?tag:"ns2:getDataResponse", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct ns2__getDataResponse * SOAP_FMAC4 soap_get_ns2__getDataResponse(struct soap *soap, struct ns2__getDataResponse *p, const char *tag, const char *type) { if ((p = soap_in_ns2__getDataResponse(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Reason)) soap_serialize_SOAP_ENV__Reason(soap, *a); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Reason *const*a, const char *type) { id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Reason, NULL); if (id < 0) return soap->error; return soap_out_SOAP_ENV__Reason(soap, tag, id, *a, type); } SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason **a, const char *type) { (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 1, NULL)) return NULL; if (!a) if (!(a = (struct SOAP_ENV__Reason **)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason *)))) return NULL; *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); if (!(*a = soap_in_SOAP_ENV__Reason(soap, tag, *a, type))) return NULL; } else { a = (struct SOAP_ENV__Reason **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a, const char *tag, const char *type) { if (soap_out_PointerToSOAP_ENV__Reason(soap, tag?tag:"SOAP-ENV:Reason", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason **p, const char *tag, const char *type) { if ((p = soap_in_PointerToSOAP_ENV__Reason(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Detail)) soap_serialize_SOAP_ENV__Detail(soap, *a); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Detail *const*a, const char *type) { id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Detail, NULL); if (id < 0) return soap->error; return soap_out_SOAP_ENV__Detail(soap, tag, id, *a, type); } SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail **a, const char *type) { (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 1, NULL)) return NULL; if (!a) if (!(a = (struct SOAP_ENV__Detail **)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail *)))) return NULL; *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); if (!(*a = soap_in_SOAP_ENV__Detail(soap, tag, *a, type))) return NULL; } else { a = (struct SOAP_ENV__Detail **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a, const char *tag, const char *type) { if (soap_out_PointerToSOAP_ENV__Detail(soap, tag?tag:"SOAP-ENV:Detail", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail **p, const char *tag, const char *type) { if ((p = soap_in_PointerToSOAP_ENV__Detail(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif #ifndef WITH_NOGLOBAL SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Code)) soap_serialize_SOAP_ENV__Code(soap, *a); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Code *const*a, const char *type) { char *mark; id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Code, &mark); if (id < 0) return soap->error; soap_out_SOAP_ENV__Code(soap, tag, id, *a, type); soap_unmark(soap, mark); return soap->error; } SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code **a, const char *type) { (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 1, NULL)) return NULL; if (!a) if (!(a = (struct SOAP_ENV__Code **)soap_malloc(soap, sizeof(struct SOAP_ENV__Code *)))) return NULL; *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); if (!(*a = soap_in_SOAP_ENV__Code(soap, tag, *a, type))) return NULL; } else { a = (struct SOAP_ENV__Code **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0, NULL); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a, const char *tag, const char *type) { if (soap_out_PointerToSOAP_ENV__Code(soap, tag?tag:"SOAP-ENV:Code", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code **p, const char *tag, const char *type) { if ((p = soap_in_PointerToSOAP_ENV__Code(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #endif SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToData(struct soap *soap, Data *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF if (!soap_reference(soap, *a, SOAP_TYPE_Data)) (*a)->soap_serialize(soap); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToData(struct soap *soap, const char *tag, int id, Data *const*a, const char *type) { id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_Data, NULL); if (id < 0) return soap->error; return (*a)->soap_out(soap, tag, id, type); } SOAP_FMAC3 Data ** SOAP_FMAC4 soap_in_PointerToData(struct soap *soap, const char *tag, Data **a, const char *type) { (void)type; /* appease -Wall -Werror */ if (soap_element_begin_in(soap, tag, 1, NULL)) return NULL; if (!a) if (!(a = (Data **)soap_malloc(soap, sizeof(Data *)))) return NULL; *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); if (!(*a = (Data *)soap_instantiate_Data(soap, -1, soap->type, soap->arrayType, NULL))) return NULL; (*a)->soap_default(soap); if (!(*a)->soap_in(soap, tag, NULL)) { *a = NULL; return NULL; } } else { a = (Data **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_Data, sizeof(Data), 0, soap_fbase); if (soap->body && soap_element_end_in(soap, tag)) return NULL; } return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToData(struct soap *soap, Data *const*a, const char *tag, const char *type) { if (soap_out_PointerToData(soap, tag?tag:"Data", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 Data ** SOAP_FMAC4 soap_get_PointerToData(struct soap *soap, Data **p, const char *tag, const char *type) { if ((p = soap_in_PointerToData(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap *soap, char **a) { (void)soap; /* appease -Wall -Werror */ #ifdef SOAP_DEFAULT__QName *a = SOAP_DEFAULT__QName; #else *a = (char *)0; #endif } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap *soap, char *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_reference(soap, *a, SOAP_TYPE__QName); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap *soap, const char *tag, int id, char *const*a, const char *type) { return soap_outstring(soap, tag, id, a, type, SOAP_TYPE__QName); } SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap *soap, const char *tag, char **a, const char *type) { a = soap_instring(soap, tag, a, type, SOAP_TYPE__QName, 2, 0, -1, NULL); return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap *soap, char *const*a, const char *tag, const char *type) { if (soap_out__QName(soap, tag?tag:"QName", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap *soap, char **p, const char *tag, const char *type) { if ((p = soap_in__QName(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap *soap, char **a) { (void)soap; /* appease -Wall -Werror */ #ifdef SOAP_DEFAULT_string *a = SOAP_DEFAULT_string; #else *a = (char *)0; #endif } SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap *soap, char *const*a) { (void)soap; (void)a; /* appease -Wall -Werror */ #ifndef WITH_NOIDREF soap_reference(soap, *a, SOAP_TYPE_string); #endif } SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap *soap, const char *tag, int id, char *const*a, const char *type) { return soap_outstring(soap, tag, id, a, type, SOAP_TYPE_string); } SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap *soap, const char *tag, char **a, const char *type) { a = soap_instring(soap, tag, a, type, SOAP_TYPE_string, 1, 0, -1, NULL); return a; } SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap *soap, char *const*a, const char *tag, const char *type) { if (soap_out_string(soap, tag?tag:"string", -2, a, type)) return soap->error; return soap_putindependent(soap); } SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap *soap, char **p, const char *tag, const char *type) { if ((p = soap_in_string(soap, tag, p, type))) if (soap_getindependent(soap)) return NULL; return p; } #if defined(__BORLANDC__) #pragma option pop #pragma option pop #endif /* End of soapC.cpp */ <file_sep>#include "soapsoapService.h" #include <time.h> int soapService::getData(std::string name, DataRep &result) { // std::string date[] = {"16:00:00","17:00:00","18:00:00"}; std::string content[] = {"test1","test2","test3"}; std::cout << "name : " << name << std::endl; result.status = true; result.message = "OK"; result.dateTime = "2016/09/01 16:14:00"; result.dataArray.__size = 3; result.quantity = result.dataArray.__size ; if ( result.dataArray.__size > 0 ) { result.dataArray.data = new Data[result.dataArray.__size]; for ( int i=0 ; i<result.dataArray.__size; i++ ) { result.dataArray.data[i].dateTime = date[i]; result.dataArray.data[i].content = content[i]; } } return SOAP_OK; } <file_sep>target=soap_test all: g++ -o ${target} soap.cpp soapsoapService.cpp main.cpp soapC.cpp stdsoap2.cpp -lpthread #-fpermissive -lpthread gen: soapcpp2 -jSL soap.h clean: rm -rf ${target} <file_sep>#include <pthread.h> #include "soap.nsmap" #include "soapsoapService.h" #include "strtool.h" using std::string; using std::vector; using std::cout; using std::endl; #define WSDL_PATH "proscan.wsdl" int rep_wsdl(struct soap *soap, string path, string params) { FILE *fd = NULL; fd = fopen(WSDL_PATH, "rb"); if (!fd) return 404; soap->http_content = "text/xml"; soap_response(soap, SOAP_FILE); for (;;) { size_t r = fread(soap->tmpbuf, 1, sizeof(soap->tmpbuf), fd); if (!r) break; if (soap_send_raw(soap, soap->tmpbuf, r)) break; } fclose(fd); soap_end_send(soap); return SOAP_OK; } int http_get(struct soap *soap) { vector<string> vt; strtool::split(soap->path, vt, "?"); if ( vt[0].compare("/proscan") == 0 ) { if ( vt.size() == 2 && vt[1].compare("wsdl") == 0 ) { return rep_wsdl(soap, vt[0] , vt[1]); } } return SOAP_GET_METHOD; } int main(int argc, char **argv) { struct soap soap; int server_port = 8080; //proscanService proscan(SOAP_XML_INDENT); soap.fget = http_get; soap.bind_flags = SO_REUSEADDR; soap.send_timeout = 60; // 60 seconds soap.recv_timeout = 60; // 60 seconds soap.accept_timeout = 3600; // server stops after 1 hour of inactivity soap.max_keep_alive = 100; // max keep-alive sequence soapService soapService(&soap); if ( argc > 2 ) { server_port = atoi(argv[1]); } if (soapService.run(server_port) != SOAP_OK) { soapService.soap_stream_fault(std::cerr); } soapService.destroy(); }
c3daa61e3c2f4e629ce1d815e5afa3744c461506
[ "Makefile", "C++" ]
7
C++
linuxxunil/gsoapExample
ba76eed9522ef0fe3d302dd14e99be9a703753ca
310c947804118ad139446ec773449668d0d99f3b
refs/heads/master
<file_sep>import os import numpy as np import itertools import matplotlib import matplotlib.pyplot as plt from scipy.spatial import ConvexHull from yahist import set_default_style set_default_style() from matplotlib import rcParams rcParams["axes.xmargin"] = 0.1 # set_defaults() srs = {2: {}, 3:{}} # nb range, nj range ; both are inclusive # set upper nj or nb to 10 or 5 if it there is a geq import ROOT as r nbs = range(2,5) njs = range(2,9) nlepsall = range(2,4) triplets = list(itertools.product(nlepsall,nbs,njs)) d_points = {2: {}, 3: {}} r.gROOT.ProcessLine(".L /home/users/namin/2018/fourtop/all/FTAnalysis/analysis/misc/signal_regions.h ") for nleps,nbtags,njets in triplets: sr = r.signal_region_ft(njets,nbtags, 100.0, 500.0, 100, 11, 11, 30, 30, 30, nleps, False) if sr < 0: continue if sr not in d_points[nleps]: d_points[nleps][sr] = [] d_points[nleps][sr].append((nbtags+0.5,njets+0.5)) d_points[nleps][sr].append((nbtags+0.5,njets-0.5)) d_points[nleps][sr].append((nbtags-0.5,njets+0.5)) d_points[nleps][sr].append((nbtags-0.5,njets-0.5)) nsrs = 18 d_namelookup = dict(zip(range(1,nsrs+1),["CRZ","CRW"]+["SR{}".format(i-1) for i in range(2,nsrs+1)])) # # 2 leps # srs[2]["CRW"] = ((2,2), (2,5)) # srs[2]["SR1"] = ((2,2), (6,6)) # srs[2]["SR2"] = ((2,2), (7,7)) # srs[2]["SR3"] = ((2,2), (8,10)) # srs[2]["SR4"] = ((3,3), (5,5)) # srs[2]["SR5"] = ((3,3), (6,6)) # srs[2]["SR6"] = ((3,3), (7,7)) # srs[2]["SR7"] = ((3,3), (8,10)) # srs[2]["SR8"] = ((4,4), (5,5)) # srs[2]["SR9"] = ((4,4), (6,6)) # srs[2]["SR10"] = ((4,4), (7,10)) # # nlep >= 3 # srs[3]["SR11"] = ((2,2), (5,5)) # srs[3]["SR12"] = ((2,2), (6,6)) # srs[3]["SR13"] = ((2,2), (7,10)) # srs[3]["SR14"] = ((3,5), (4,4)) # srs[3]["SR15"] = ((3,5), (5,5)) # srs[3]["SR16"] = ((3,5), (6,10)) # def get_hull(ranges): # nbrange, njrange = np.array(ranges,dtype=float) # pad = False # if pad: # nbrange[0] -= 0.475 # njrange[0] -= 0.445 # nbrange[1] += 0.475 # njrange[1] += 0.445 # else: # nbrange[0] -= 0.5 # njrange[0] -= 0.5 # nbrange[1] += 0.5 # njrange[1] += 0.5 # corners = np.array([ # [nbrange[0], njrange[0]], # [nbrange[1], njrange[0]], # [nbrange[0], njrange[1]], # [nbrange[1], njrange[1]], # ]) # return corners, ConvexHull(corners) def get_hull(points): return np.array(points), ConvexHull(points) fig, (ax2, ax3) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(6,4)) def plot_one(ax, srs, title=""): for srname in srs: # points, hull = get_hull(srs["CRW"]) points, hull = get_hull(srs[srname]) cx, cy = points[hull.vertices].mean(axis=0) for simplex in hull.simplices: edgeb, edgej = points[simplex, 0], points[simplex, 1] style = "C3-" if (edgej[0] == edgej[1]) and (edgej[0] > 8): style = "C3--" if (edgeb[0] == edgeb[1]) and (edgeb[0] > 4): style = "C3--" ax.plot(edgeb, edgej, style, linewidth=1.5) ax.text(cx,cy,d_namelookup[srname], horizontalalignment="center", verticalalignment="center", fontsize=12) ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True)) ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True)) ax.set_title(title) ax.set_xlabel("number of b-tagged jets") if "3" not in title: ax.set_ylabel("number of jets") # ax.set_aspect('equal') ax.grid(True) plot_one(ax2, d_points[2], title="number of leptons = 2") plot_one(ax3, d_points[3], title="number of leptons $\\geq$ 3") # plot_one(ax2, srs[2], title="# leptons = 2") # plot_one(ax3, srs[3], title="# leptons = 3") fig.tight_layout() fig.savefig("srplot.pdf") os.system("ic srplot.pdf") <file_sep>## This is not my thesis ### Progress ![](figs/misc/progress.png) <file_sep>import matplotlib.pyplot as plt import os from yahist import Hist1D, set_default_style import uproot set_default_style() # bins = "250,0,750" # fname = "/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.31/output/year_2018/T1TTTT.root" # t = uproot.open(fname)["t"] # mtmin, hypclass = t["mtmin"].array(), t["hyp_class"].array() # mtmin = mtmin[hypclass==3] # Hist1D(mtmin, bins=bins).to_json("hist_mtmin_signal.json") # fname = "/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.31/output/year_2018/TTBAR_PH.root" # t = uproot.open(fname)["t"] # mtmin, hypclass = t["mtmin"].array(), t["hyp_class"].array() # mtmin = mtmin[hypclass==3] # Hist1D(mtmin, bins=bins).to_json("hist_mtmin_ttbar.json") h_signal = Hist1D.from_json("hist_mtmin_signal.json") h_ttbar = Hist1D.from_json("hist_mtmin_ttbar.json") h_signal = h_signal.normalize() h_ttbar = h_ttbar.normalize() fig, ax = plt.subplots() h_signal.plot(histtype="step", label="signal (T1tttt)", color="C3", gradient=True) h_ttbar.plot(histtype="step", label=r"background ($t\bar{t}$ + jets)", color="C0", gradient=True) ax.axvline(84., color="gray") ax.text(1.1*84., 0.03, "$m_{W}$", fontsize=14, color="gray") ax.set_yscale("log") ax.set_ylabel("Frac. of events") ax.set_xlabel(r"$m_\mathrm{T}^\mathrm{min}$ (GeV)") xtype = 0.10 typ = "Simulation" ax.text(0.0, 1.01,"CMS", horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, weight="bold", size=15) ax.text(xtype, 1.01,typ, horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, style="italic", size=15) ax.text(0.99, 1.01,"(13 TeV)", horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size=14) fig.set_tight_layout(True) ax.legend(fontsize=12) fig.savefig("mtmin_signal_ttbar.pdf") os.system("ic mtmin_signal_ttbar.pdf") <file_sep>import json import os import numpy as np import itertools import re import sys import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.patches as mpatches import matplotlib.lines as mlines from matplotlib.ticker import MultipleLocator from scipy import interpolate from yahist import set_default_style set_default_style() # def add_cms_info(ax, typ="", lumi="137", xtype=0.12): # ax.text(0.0, 1.01,"CMS", horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, weight="bold", size=20) # ax.text(xtype, 1.01,typ, horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, style="italic", size="x-large") # ax.text(0.99, 1.01,"%s fb${}^\mathregular{-1}$ (13 TeV)" % (lumi), horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size="x-large") def add_cms_info(ax, typ="", lumi="137", xtype=0.12): ax.text(0.99, 1.01,"(13 TeV)", horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size="x-large") def load_data(fname="data/ftinterpretations_data.txt"): data = [] with open(fname,"r") as fh: for line in fh: parts = line.strip().split(":") if not parts: continue if "hadoop" in parts[0]: folder = "" proctag = parts[0].rsplit("/",1)[-1].rsplit(".",1)[0] xsec = float(parts[-1].strip()) else: folder = parts[0].split("/Events",1)[0].rsplit("/",2)[-2] proctag = parts[0].split("/Events",1)[0].rsplit("/",1)[-1] xsec = float(parts[-1].strip()) data.append(dict(folder=folder,tag=proctag,xsec=xsec)) df = pd.DataFrame(data) return df def get_df(g11=True): if g11: df = load_data("data/data_dm_v4.txt") else: df = load_data("data/data_dm_v5.txt") df = df[df.tag.str.contains("dmscalar") | df.tag.str.contains("dmpseudo")] print(df.tag) df["which"] = df.tag.str.split("_").str[0] df["proc"] = df.tag.str.split("_").str[1] df["massmed"] = df.tag.str.split("_").str[2].astype(int) df["massdm"] = df.tag.str.split("_").str[3].astype(int) df = df.drop(["tag","folder"],axis=1) # separate 6 processes ttdm = df[df.proc=="ttdm"].rename(index=str,columns={"xsec":"xsec_ttdm"}).drop(["proc"],axis=1) ttsm = df[df.proc=="ttsm"].rename(index=str,columns={"xsec":"xsec_ttsm"}).drop(["proc"],axis=1) stwdm = df[df.proc=="stwdm"].rename(index=str,columns={"xsec":"xsec_stwdm"}).drop(["proc"],axis=1) stwsm = df[df.proc=="stwsm"].rename(index=str,columns={"xsec":"xsec_stwsm"}).drop(["proc"],axis=1) sttdm = df[df.proc=="sttdm"].rename(index=str,columns={"xsec":"xsec_sttdm"}).drop(["proc"],axis=1) sttsm = df[df.proc=="sttsm"].rename(index=str,columns={"xsec":"xsec_sttsm"}).drop(["proc"],axis=1) # make dataframe where each row contains all 6 processes, and sum up xsecs # print ttdm dfc = ttdm for x in [ttsm,stwdm,stwsm,sttdm,sttsm]: dfc = dfc.merge(x,suffixes=["",""],on=["which","massmed","massdm"],how="outer") # dfc = dfc.fillna(0.) # FIXME # dfc = dfc.fillna(15.e-3) # FIXME dfc["xsec_totdm"] = dfc["xsec_ttdm"] + dfc["xsec_stwdm"] + dfc["xsec_sttdm"] dfc["xsec_totsm"] = dfc["xsec_ttsm"] + dfc["xsec_stwsm"] + dfc["xsec_sttsm"] dfc["stfrac_sm"] = (dfc["xsec_stwsm"] + dfc["xsec_sttsm"])/dfc["xsec_totsm"] dfc["stfrac_dm"] = (dfc["xsec_stwdm"] + dfc["xsec_sttdm"])/dfc["xsec_totdm"] return dfc def grid(x, y, z, resX=100j, resY=100j): from scipy.interpolate import griddata xi, yi = np.mgrid[min(x):max(x):resX, min(y):max(y):resY] # Z = griddata((x, y), z, (xi[None,:], yi[None,:]), method="linear") #, interp="linear") Z = griddata((x, y), z, (xi[None,:], yi[None,:]), method="linear") #, interp="linear") Z = Z[0] return xi, yi, Z dfc1 = get_df(g11=True) dfc2 = get_df(g11=False) do_scatter = True for which in [ "dmscalar", "dmpseudo", ]: for key in [ "xsec_totsm", # "stfrac_sm", # "xsec_totdm", # "stfrac_dm", ]: do_exclusion = False # fig,ax = plt.subplots() fig, ax = plt.subplots(gridspec_kw={"top":0.92,"bottom":0.14,"left":0.15,"right":0.95},figsize=(5.5,5.5)) # which = "dmscalar" # which = "dmpseudo" # key = "xsec_totdm" # key = "xsec_totsm" df1 = dfc1[dfc1["which"] == which] df2 = dfc2[dfc2["which"] == which] if do_scatter: ax.scatter(df1["massmed"],df1["massdm"],c=df1[key], # ax.scatter(df2["massmed"],df2["massdm"],c=df2[key], # norm=mpl.colors.LogNorm(vmin=1.5*1e-4,vmax=200*1e-3), norm=mpl.colors.LogNorm( vmin=max(df1[key].min(),0.001), vmax=min(df1[key].max(),150.), ), cmap='cividis', # cmap='Blues', ) data_rvals1 = [] data_rvals2 = [] if "frac" in key: for i,(massmed,massdm,val) in df1[["massmed","massdm",key]].iterrows(): s = "{:.2f}".format(val) if do_scatter: ax.text(massmed,massdm+8.,s,fontsize=7,horizontalalignment="center",verticalalignment="bottom") else: for i,(massmed,massdm,xsec) in df1[["massmed","massdm",key]].iterrows(): xsec = xsec*1e3 color = "k" if not np.isfinite(xsec): continue if xsec >= 100.: s = "{:.0f}".format(xsec) elif xsec >= 10.: s = "{:.1f}".format(xsec) elif xsec >= 1.: s = "{:.1f}".format(xsec) else: s = "{:.2f}".format(xsec) if do_scatter: ax.text(massmed,massdm+8.,s,fontsize=6,horizontalalignment="center",verticalalignment="bottom",color=color) for i,(massmed,massdm,xsec) in df2[["massmed","massdm",key]].iterrows(): xsec = xsec*1e3 if "dm" in key: title = r"DM+X, X=$\mathrm{{t\bar{{t}}}}$,tW,tq [{}]".format(which[2:]) else: title = r"$\mathrm{{t\bar{{t}}}}$+X, X=$\mathrm{{t\bar{{t}}}}$,tW,tq [{}]".format(which[2:]) minx = 300. miny = 0. maxy = 700. maxx = 750. ax.set_xlim([minx,maxx]) ax.set_ylim([miny,maxy]) line = ax.plot([250,800],[0.5*250,0.5*800],linestyle="-",color="k",alpha=0.3) p1 = ax.transData.transform_point((minx,0.5*minx)) p2 = ax.transData.transform_point((maxx,0.5*maxy)) angle = np.degrees(np.arctan2(*(p2-p1)[::-1])) # ax.text(maxx,0.5*maxy-40,r"$\mathrm{m}_\mathrm{med}<2 \mathrm{m}_\mathrm{DM}$ ",fontsize=10,horizontalalignment="right",verticalalignment="bottom",rotation=angle, color="0.3") if "pseudo" in which: ax.text(maxx,0.5*maxy-0,r"$m_\mathrm{A}<2 m_\chi$ ",fontsize=10,horizontalalignment="right",verticalalignment="bottom",rotation=angle, color="0.3") else: ax.text(maxx,0.5*maxy-0,r"$m_\mathrm{H}<2 m_\chi$ ",fontsize=10,horizontalalignment="right",verticalalignment="bottom",rotation=angle, color="0.3") if "pseudo" in which: # ax.text((maxx-minx)*0.8+minx,maxy*0.8,"pseudoscalar\nmediator",fontsize=14,horizontalalignment="center",verticalalignment="center",color="k") ax.text((maxx-minx)*0.8+minx,maxy*0.8,"pseudoscalar",fontsize=15,horizontalalignment="center",verticalalignment="center",color="k") else: # ax.text((maxx-minx)*0.8+minx,maxy*0.8,"scalar\nmediator",fontsize=14,horizontalalignment="center",verticalalignment="center",color="k") ax.text((maxx-minx)*0.8+minx,maxy*0.8,"scalar",fontsize=15,horizontalalignment="center",verticalalignment="center",color="k") print(which) # text = ax.set_title(title) # ax.set_ylabel(r"DM mass") ax.set_ylabel(r"$m_\chi$ (GeV)") # ax.set_xlabel(r"mediator mass") if "pseudo" in which: ax.set_xlabel(r"$m_\mathrm{A}$ (GeV)") else: ax.set_xlabel(r"$m_\mathrm{H}$ (GeV)") ax.yaxis.set_minor_locator(MultipleLocator(25.)) ax.xaxis.set_minor_locator(MultipleLocator(25.)) add_cms_info(ax, lumi="137") # ax.xaxis.set_minor_locator(MultipleLocator(10.)) fig.set_tight_layout(True) # fig.set_tight_layout() if do_scatter: fname = "plot_2d_{}_{}.pdf".format(which,key) else: fname = "plot_2d_{}_{}_bothcouplings.pdf".format(which,key) fig.savefig(fname) os.system("ic "+fname) <file_sep>import sys import numpy as np sys.path.insert(0,'/home/users/namin/.local/lib/python2.7/site-packages/') import os import pandas as pd from mytqdm import tqdm import matplotlib as mpl mpl.use('Agg') from matplotlib import rcParams import matplotlib.pyplot as plt from matplottery.utils import Hist1D from matplottery.plotter import plot_stack import uproot import itertools import root_numpy as rn np.set_printoptions(linewidth=150) # colors from https://github.com/sgnoohc/Ditto/blob/master/python/makeplot.py#L193-L200 info_multitop = [ ("TTWW" , [ 0/255. , 114/255. , 178/255.]), ("TTTW" , [ 86/255. , 180/255. , 233/255.]), ("TTWZ" , [ 0/255. , 158/255. , 115/255.]), ("TTWH" , [240/255. , 228/255. , 66/255.]), ("TTHH" , [230/255. , 159/255. , 0/255.]), ("TTZH" , [213/255. , 94/255. , 0/255.]), ("TTTJ" , [204/255. , 121/255. , 167/255.]), ("TTZZ" , [140/255. , 93/255. , 119/255.]), ] info_multiboson = [ ("TZQ" , [ 0/255. , 114/255. , 178/255.]), # ("WWDPS" , [ 86/255. , 180/255. , 233/255.]), ("QQWW" , [ 86/255. , 180/255. , 233/255.]), ("TWZ" , [ 0/255. , 158/255. , 115/255.]), ("WZZ" , [240/255. , 228/255. , 66/255.]), ("ZZ" , [230/255. , 159/255. , 0/255.]), # ("GGHtoZZto4L" , [213/255. , 94/255. , 0/255.]), ("WWDPS" , [204/255. , 121/255. , 167/255.]), ("VHtoNonBB" , [140/255. , 93/255. , 119/255.]), ("WW[GWZ]" , [110/255. , 54/255. , 0/255.]), ] def transform_label(x): if "[" in x: toexplode = x.split("[")[-1].split("]")[0] x = x.replace(toexplode,",".join(toexplode)) x = x.replace("[","{").replace("]","}").replace("T","t").replace("Q","q").replace("G",r"$\gamma$") x = x.replace("to",r"$\rightarrow$") x = x.replace("BB",r"$b\bar{b}$") x = x.replace("tt",r"t$\bar{\mathrm{t}}$") return x # fname_patt = "/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.13_all/output/year_2016/{}.root" # fname_patt = "/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.13_all/output/year_2017/{}.root" for which,info in zip(["multitop","multiboson"],[info_multitop,info_multiboson]): hists = [] bins = np.arange(0.5,17.5-2,1) for stag,color in info: tmp = [] for year in [2016,2017,2018]: fname_patt = "/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.24/output/year_%i/{}.root" % year try: arr = rn.root2array(fname_patt.format(stag),"t",branches=["sr-2", "{}*scale1fb".format({2016:35.9,2017:41.5,2018:58.8}[year])], selection="hyp_class==3 && br && fired_trigger && passes_met_filters && sr>2") arr.dtype.names = ( "sr-2", "weight",) label = transform_label(stag) h = Hist1D(arr["sr-2"], weights=arr["weight"],bins=bins, label=label,color=color) tmp.append(h) except: print "ERROR with {} for {}".format(stag,year) continue h = sum(tmp) hists.append(h) fname = "plots_rares/h_{}.pdf".format(which) plot_stack( bgs=hists[::-1], filename=fname, do_log=False, # xlabel="SR", ylabel="Events", title="{}".format(which), lumi = 35.9+41.5+58.8, cms_type = "Preliminary", do_bkg_syst=True, xticks = ["SR{}".format(i) for i in range(1,20)], mpl_xtick_params=dict(fontsize=8,rotation=45), ) os.system("ic {}".format(fname)) <file_sep>all: build log .PHONY: clean clean: rm -f *.blg rm -f *.out rm -f *.bbl rm -f *.log rm -f *.ind rm -f *.ilg rm -f *.lot rm -f *.lof rm -f *.idx rm -f *.aux rm -f *.toc rm -f thesis.pdf rm -f output.pdf rm -f smalloutput.pdf rm -f *.fdb_latexmk rm -f *.fls rm -f *.synctex.gz plot: python3 scripts/plot_progress.py log: pdfinfo output.pdf -isodates | grep -E "(CreationDate|Pages|File size)" | xargs echo >> logs/size_log.txt tail -1 logs/size_log.txt build: latexmk -synctex=1 -interaction=nonstopmode -file-line-error -pdf thesis.tex cp thesis.pdf output.pdf buildold: pdflatex -shell-escape -jobname output -draftmode thesis.tex -interaction=batchmode pdflatex -shell-escape -jobname output thesis.tex -interaction=batchmode bibtex output makeindex thesis.tex pdflatex -shell-escape -jobname output -draftmode thesis.tex -interaction=batchmode pdflatex -shell-escape -jobname output thesis.tex mkdir -p tmp mv *.{ind,blg,out,bbl,log,ilg,aux,toc} tmp/ # single spaced small version small: pdflatex -shell-escape -jobname smalloutput "\def\myownflag{}\input{thesis}" -interaction=batchmode # mv -f *.{out,log,aux,toc,4ct,4tc,tmp,xref} tmp/ mv -f *.{out,log,aux,toc} tmp/ push: git commit -a -m "update" git push <file_sep>mv Figure_002-a.pdf sr_njets_prefit.pdf mv Figure_002-b.pdf sr_nbtags_prefit.pdf mv Figure_002-c.pdf sr_ht_prefit.pdf mv Figure_002-d.pdf sr_met_prefit.pdf mv Figure_003-a.pdf ttwcr_njets_prefit.pdf mv Figure_003-b.pdf ttwcr_nbtags_prefit.pdf mv Figure_003-c.pdf ttzcr_njets_prefit.pdf mv Figure_003-d.pdf ttzcr_nbtags_prefit.pdf mv Figure_004-a.pdf SRCR_postfit.pdf mv Figure_004-b.pdf SRDISC_postfit.pdf mv Figure_005.pdf yukawa.pdf mv Figure_006.pdf plot_2d_phizprime.pdf mv Figure_007-a.pdf ft_higgs_sc_scan_limit.pdf mv Figure_007-b.pdf ft_higgs_ps_scan_limit.pdf mv Figure_008-a.pdf plot_2d_2hdm_tanbetaexclusion_h.pdf mv Figure_008-b.pdf plot_2d_2hdm_tanbetaexclusion_a.pdf mv Figure_008-c.pdf plot_2d_2hdm_tanbetaexclusion_b.pdf mv Figure_009-a.pdf plot_2d_dmscalar_xsec_totsm_bothcouplings.pdf mv Figure_009-b.pdf plot_2d_dmpseudo_xsec_totsm_bothcouplings.pdf <file_sep>import sys import os import numpy as np import sys import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.patheffects as meffects import matplotlib.font_manager as mfm import pandas as pd import pickle import fnmatch import glob import ast from matplotlib.ticker import MultipleLocator import os import matplotlib.pyplot as plt # # SIGH # import matplotlib # matplotlib.rcParams['xtick.direction'] = 'in' # matplotlib.rcParams['ytick.direction'] = 'in' XSEC_TTTT = 11.97 GREEN = (0.,0.8,0.) YELLOW = (1.,0.8,0.) def set_defaults(): from matplotlib import rcParams rcParams["font.family"] = "sans-serif" rcParams["font.sans-serif"] = ["Helvetica", "Arial", "Liberation Sans", "Bitstream Vera Sans", "DejaVu Sans"] rcParams['legend.fontsize'] = 13 rcParams['legend.labelspacing'] = 0.2 rcParams['axes.xmargin'] = 0.0 # rootlike, no extra padding within x axis rcParams['axes.labelsize'] = 'x-large' rcParams['axes.formatter.use_mathtext'] = True rcParams['legend.framealpha'] = 0.65 rcParams['axes.labelsize'] = 'x-large' rcParams['axes.titlesize'] = 'x-large' rcParams['xtick.labelsize'] = 'x-large' rcParams['ytick.labelsize'] = 'x-large' rcParams['figure.subplot.hspace'] = 0.1 rcParams['figure.subplot.wspace'] = 0.1 rcParams['figure.subplot.right'] = 0.96 rcParams['figure.max_open_warning'] = 0 rcParams['figure.dpi'] = 125 rcParams["axes.formatter.limits"] = [-5,4] # scientific notation if log(y) outside this # def add_cms_info(ax, typ="", lumi="137", xtype=0.12): # ax.text(0.0, 1.01,"CMS", horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, weight="bold", size=20) # ax.text(xtype, 1.01,typ, horizontalalignment='left', verticalalignment='bottom', transform = ax.transAxes, style="italic", size="x-large") # ax.text(0.99, 1.01,"%s fb${}^\mathregular{-1}$ (13 TeV)" % (lumi), horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size="x-large") def add_cms_info(ax, typ="", lumi="137", xtype=0.12): ax.text(0.99, 1.01,"(13 TeV)", horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size="x-large") def get_fig_ax(): fig, ax = plt.subplots(gridspec_kw={"top":0.92,"bottom":0.14,"left":0.15,"right":0.95},figsize=(5.5,5.5)) return fig, ax class DoubleBandObject(object): pass class DoubleBandObjectHandler(object): def legend_artist(self, legend, orig_handle, fontsize, handlebox): x0, y0 = handlebox.xdescent, handlebox.ydescent width, height = handlebox.width, handlebox.height patch = mpatches.Rectangle([x0, y0-height*0.25], width, height*1.5, facecolor=YELLOW, edgecolor="none", lw=0., transform=handlebox.get_transform()) handlebox.add_artist(patch) patch = mpatches.Rectangle([x0, y0+0.25*height*1.5-height*0.25], width, height*1.5*0.5, facecolor=GREEN, edgecolor="none", lw=0., transform=handlebox.get_transform()) handlebox.add_artist(patch) patch = mlines.Line2D( [x0+width*0.03,x0+width-width*0.03],[y0-height*0.25+height*0.75],color=(0.,0.,0.),linewidth=1,linestyle="--", transform=handlebox.get_transform(), ) handlebox.add_artist(patch) return patch class OneSideHatchObject(object): pass class OneSideHatchObjectHandler(object): def legend_artist(self, legend, orig_handle, fontsize, handlebox): x0, y0 = handlebox.xdescent, handlebox.ydescent width, height = handlebox.width, handlebox.height patch = mlines.Line2D( [x0+width*0.03,x0+width-width*0.03],[y0+height*0.2,y0+height*0.2],color=(0.4,0.4,0.4),linewidth=2,linestyle="-", transform=handlebox.get_transform(), ) handlebox.add_artist(patch) patch = mpatches.Rectangle([x0, y0+height*0.2], width, height-height*0.2, facecolor='none', edgecolor=(0.4,0.4,0.4), hatch='///', lw=0., transform=handlebox.get_transform()) handlebox.add_artist(patch) return patch def make_yukawa_plot(): # A: gza # B: int # F: higgs def calc_sigma(kt,A,B,F): return A + B*kt**2 + F*kt**4 # kfactor such that xsec=11.97 at kt=1 kfactor = 1.2445 gza_13tev = 9.997*kfactor int_13tev = -1.547*kfactor higgs_13tev = 1.168*kfactor # scale variations for 13 tev numbers gza_13tev_up = 14.104*kfactor int_13tev_up = -2.152*kfactor higgs_13tev_up = 1.625*kfactor gza_13tev_down = 6.378*kfactor int_13tev_down = -0.999*kfactor higgs_13tev_down = 0.7655*kfactor kts_fine = np.linspace(0.,3.0,31.) theory_cent = calc_sigma(kts_fine,gza_13tev,int_13tev,higgs_13tev) theory_down = calc_sigma(kts_fine,gza_13tev_down,int_13tev_down,higgs_13tev_down) theory_up = calc_sigma(kts_fine,gza_13tev_up,int_13tev_up,higgs_13tev_up) fig,ax = get_fig_ax() add_cms_info(ax) p1 = ax.fill_between(kts_fine, theory_down, theory_up, linewidth=0., facecolor="C0", alpha=0.3) p2 = ax.plot(kts_fine, theory_cent, linestyle="--", marker="",color=(0.04,0.16,0.31)) legend = ax.legend( [ (p1,p2[0]), ], [ "Predicted cross section", ], handler_map={OneSideHatchObject: OneSideHatchObjectHandler()}, labelspacing=0.6, fontsize=12, ) ax.xaxis.set_minor_locator(MultipleLocator(0.1)) ax.yaxis.set_minor_locator(MultipleLocator(2)) ax.axvline(1., color="gray") ax.text(1.1, 40., "SM", color="gray", fontsize=14) ax.set_ylim([0.,55.]) ax.set_ylabel(r"$\sigma_{t\bar{t}t\bar{t}}$ (fb)") ax.set_title("") ax.set_xlabel(r"$|y_\mathrm{t}\ /\ y_\mathrm{t}^\mathrm{SM}|$") fig.set_tight_layout(True) fname = "cross_section_yt.pdf" fig.savefig(fname) os.system("ic {}".format(fname)) print("Saved {}".format(fname)) if __name__ == "__main__": set_defaults() make_yukawa_plot() <file_sep>import json import os import numpy as np import itertools import re import sys import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.ticker import MultipleLocator import matplotlib.patches as mpatches import matplotlib.lines as mlines from scipy import interpolate from yahist import set_default_style set_default_style() def add_cms_info(ax, typ="", lumi="137", xtype=0.12): ax.text(0.99, 1.01,"(13 TeV)", horizontalalignment='right', verticalalignment='bottom', transform = ax.transAxes, size="x-large") def load_data(fname="data/ftinterpretations_data.txt"): data = [] with open(fname,"r") as fh: for line in fh: parts = line.strip().split(":") if not parts: continue if "hadoop" in parts[0]: folder = "" proctag = parts[0].rsplit("/",1)[-1].rsplit(".",1)[0] xsec = float(parts[-1].strip()) else: folder = parts[0].split("/Events",1)[0].rsplit("/",2)[-2] proctag = parts[0].split("/Events",1)[0].rsplit("/",1)[-1] xsec = float(parts[-1].strip()) data.append(dict(folder=folder,tag=proctag,xsec=xsec)) df = pd.DataFrame(data) return df def plot_crossings(df, ul=2.,which="phi"): fig, ax = plt.subplots(nrows=1, ncols=1) edges = [] masses = sorted(df["mass"].unique()) print(len(masses)) import matplotlib cmap = matplotlib.cm.get_cmap("magma") colors = cmap(np.linspace(0,0.8,len(masses))) for color,mass in zip(colors,masses): # for mass in masses: sel = df["mass"]==mass xs = df["coupling"][sel] ys = df["ratio"][sel] # mask that returns unique elements (assuming xs is sorted, which it is) uniq = np.array([True]+(np.diff(xs)!=0).tolist()) xs = xs[uniq] ys = ys[uniq] label = "{:.0f}GeV".format(mass) # ax.plot(xs,ys,label=label,markersize=5.,marker="o") ax.plot(xs,ys,label=label,markersize=5.,marker="o", color=color) if len(xs) >= 3: fint = interpolate.interp1d(xs,ys,kind="quadratic") xnew = np.linspace(xs.min(),xs.max(),100.) ynew = fint(xnew) # ax.plot(xnew,ynew,linewidth=1.0,color="k") # ax.plot(xnew,ynew,linewidth=1.0,color=color) if ynew.min() < ul < ynew.max(): big_xy = np.c_[np.linspace(xs.min(),xs.max(),1000),fint(np.linspace(xs.min(),xs.max(),1000))] xcross = big_xy[np.abs(big_xy[:,1]-ul).argmin()][0] edges.append([mass,xcross]) # ax.plot([xcross,xcross],[0.,ul*1.5],linewidth=1.0,color="k",linestyle="--") ax.plot([xcross,xcross],[0.,ul*1.5],linewidth=1.0,color=color,linestyle="--") ax.plot([0.,1.5],[ul,ul],label="",color="k",linestyle="--") ax.set_ylim([1.,ax.get_ylim()[1]]) ax.set_ylabel(r"$\sigma_\mathrm{NP+SM}/\sigma_\mathrm{SM}$") if which == "phi": ax.set_title(r"scalar $\phi$: $\sigma_\mathrm{NP+SM}/\sigma_\mathrm{SM}$ vs $g_\mathrm{t\phi}$", fontsize=14) ax.set_xlabel(r"$g_\mathrm{t\phi}$") ax.set_xlim([0.6,1.6]) else: ax.set_title(r"vector $Z'$: $\sigma_\mathrm{NP+SM}/\sigma_\mathrm{SM}$ vs $g_\mathrm{tZ'}$", fontsize=14) ax.set_xlabel(r"$g_\mathrm{tZ'}$") ax.legend(loc="upper right") ax.xaxis.set_minor_locator(MultipleLocator(0.05)) add_cms_info(ax) # ax.set_yscale("log") fig.tight_layout() fig.savefig("plot_xsec_{}.pdf".format(which)) os.system("ic plot_xsec_{}.pdf".format(which)) edges = np.array(edges) edges = np.concatenate([edges,[[340.,2.0],[25.,2.0]]]) return edges if __name__ == "__main__": d_edges = {} for which in ["zprime","phi"]: # for which in ["zprime"]: df = load_data() df = df[df.tag.str.contains(which)] df["mass"] = df.tag.str.split("_").str[2].astype(int) df["coupling"] = df.tag.str.split("_").str[3].str.replace("p",".").astype(float) df = df.drop(["tag"],axis=1) df = df.sort_values(["mass","coupling"]) xsec_sm = df[df.coupling==0.]["xsec"].values.min() df["ratio"] = df["xsec"]/xsec_sm # ratio wrt SM (smallest xsec in the list) edges = plot_crossings(df,which=which) d_edges[which] = edges <file_sep>#!/usr/bin/env python3 import os import json import numpy as np import pandas as pd import matplotlib.pyplot as plt from yahist import set_default_style set_default_style() def plot_one(ax, df, label, scale=1, color=None): baseline = ax.plot(df.mass_GeV, scale*df.xsec_pb, label = label, color=color) if "unc_up_pb" in df.columns: band = ax.fill_between(df.mass_GeV, scale*df.xsec_pb + scale*df.unc_down_pb, scale*df.xsec_pb + scale*df.unc_up_pb, alpha = 0.2, facecolor = baseline[0].get_color(), linewidth=0) else: band = ax.fill_between(df.mass_GeV, scale*df.xsec_pb - scale*df.unc_pb , scale*df.xsec_pb + scale*df.unc_pb , alpha = 0.2, facecolor = baseline[0].get_color(), linewidth=0) filenames = [ "pp13_gluino_NNLO+NNLL.json", "pp13_gluinosquark_NNLO+NNLL.json", "pp13_squark_NNLO+NNLL.json", "pp13_stopsbottom_NNLO+NNLL.json", ] fig, ax = plt.subplots() # load data and plot colors = ["C0","C1","C2","C3","C4","C5"] for color,filename in zip(colors,filenames): print(filename) data = json.load(open(os.path.join("data/susyjsons/", filename))) df = pd.DataFrame.from_dict(data["data"], orient = "index") df["mass_GeV"] = df.index.astype(int) df = df.sort_values("mass_GeV") df.reset_index(inplace = True, drop = True) # plot latex = data["process_latex"] plot_one(ax, df, latex, scale=1e3, color=color) print(latex) # for letter in "gqb": # latex = latex.replace(r"\tilde %s"%(letter), r"\tilde{\mathrm{%s}}"%(letter)) m = 2000 if "_stopsbottom_" in filename: m = 1800 tmp = df[df["mass_GeV"] == m] x, y = tmp["mass_GeV"], tmp["xsec_pb"]*1e3 # x, y = 1750, df["xsec_pb"].iloc[-1] # print(x,y) y *= 0.8 if "_stopsbottom_" in filename: y *= 0.4 ax.text(x,y,latex, color=color, rotation=-30, fontsize=14) # draw legend and style plot ax.set_xlabel("particle mass [GeV]") ax.set_ylabel("cross section [fb]") ax.set_yscale("log") ax.grid(True) ax.set_xlim(100, 2500) ax.set_ylim(1e-5*1e3, 1e2*1e3) # ax.legend(ncol = 2, framealpha = 1) # ax.legend(ncol = 2) # ax.locator_params(axis = "y", base = 100) # for log-scaled axis, it's LogLocator, not MaxNLocator from matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter ax.set_title("$\mathit{pp}$, $\sqrt{\mathit{s}}$ = 13 TeV, NLO+NLL - NNLO$_\mathregular{approx}$+NNLL", fontsize = 12) ax.xaxis.set_minor_locator(MultipleLocator(100.)) ax.yaxis.set_major_locator(LogLocator(base=10., subs=(1.,))) ax.yaxis.set_minor_locator(LogLocator(base=10., subs=np.arange(2,10)*0.1)) fig.set_tight_layout(True) fig.savefig("plot_susy_xsecs.pdf") os.system("ic plot_susy_xsecs.pdf") <file_sep>#!/usr/bin/env python3 # coding: utf-8 import os import sys import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt import matplotlib as mpl from scipy import ndimage from matplotlib import rcParams rcParams["font.family"] = "sans-serif" rcParams["font.sans-serif"] = ["Helvetica", "Arial", "Liberation Sans", "Bitstream Vera Sans", "DejaVu Sans"] rcParams['legend.fontsize'] = 12 rcParams['axes.labelsize'] = 'x-large' from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # plt.xkcd() basedir = "/Users/namin/sandbox/notmythesis" data = [] with open("{}/logs/size_log.txt".format(basedir),"r") as fh: for line in fh: if not line.strip(): continue date, _, pages, _, _, b = line.strip().split()[1:-1] date = date.rsplit("-",1)[0] data.append([date,int(pages),int(b)*1.e-3]) df = pd.DataFrame(data,columns=["date","pages","kb"]) df["date"] = pd.to_datetime(df["date"]) # df = df.set_index("date")["2020":].reset_index() df = df.set_index("date")["2020-07-23":].reset_index() fig,ax = plt.subplots() ax.plot(df["date"],df["pages"],label="actual", marker=".") ax.set_ylim([0.,230.]) ax.set_ylabel("PDF page count") deadline = datetime.date(2020,8,24) plt.axvline(deadline,color="gray") ax.text(deadline,ax.get_ylim()[1],"actual deadline ",horizontalalignment="right",verticalalignment="top",rotation=90,color="gray",fontsize=12) p = mpl.patches.Rectangle((0.,0.),height=1.0,width=0.68,transform=ax.transAxes) ax.grid(axis="both",linewidth=0.5,alpha=0.5,clip_path=p) xdeadline = mpl.dates.date2num(deadline) def data_to_fig(x,y): return fig.transFigure.inverted().transform(ax.transData.transform((x,y))) xfirst = mpl.dates.date2num(df["date"].values[0]) xlatest = mpl.dates.date2num(df["date"].values[-1]) yfirst = df["pages"].values[0] ylatest = df["pages"].values[-1] x0, y0 = ax.get_xlim()[0],ax.get_ylim()[0] x1, y1 = ax.get_xlim()[1],ax.get_ylim()[1] # ax.set_xlim([None, ax.get_xlim()[1]+90]) ax.set_xlim([None, ax.get_xlim()[1]+15]) slope = (ylatest-yfirst)/(xlatest-xfirst) xs = np.linspace(xlatest,xdeadline,100) xnorms = (xs-xlatest)/(xs.max()-xs.min()) ys_high = (ylatest + slope*1.5*(xs-xlatest))*np.exp(-5*xnorms) ys_low = (ylatest + slope*0.7*(xs-xlatest))*np.exp(-8*xnorms) ax.fill_between(xs,ys_low,ys_high,color="C0",alpha=0.25,label="projected 95% \nlack-of-confidence-in-myself \nbands") ax.legend() p = mpl.patches.Rectangle((xdeadline,0.),height=ax.get_ylim()[1],width=(ax.get_xlim()[1]-xdeadline),transform=ax.transData,edgecolor=(0.7,0.7,0.7),hatch="///",facecolor="none") ax.add_patch(p) fig.autofmt_xdate() fig.set_tight_layout(True) fig.savefig("{}/figs/misc/progress.png".format(basedir)) os.system("ic {}/figs/misc/progress.png".format(basedir)) <file_sep>import subprocess import json import os import numpy as np import itertools import re import sys import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.ticker import MultipleLocator import matplotlib.patches as mpatches import matplotlib.lines as mlines from scipy import interpolate from yahist import set_default_style set_default_style() BDTOBSUL = 22.5 XSEC_TTTT = 11.97 def get_df(s): cmd = """grep -E "(# hhat|Integrated weight)" /home/users/namin/2018/fourtop/all/FTAnalysis/studies/FTInterpretations/runs/out_oblique_scan_v1/{s}*/Events/run_*/*_tag_1_banner.txt | xargs -L 2 echo | awk '{{print $3" "$11}}'""".format(s=s) data = map(lambda x:map(float,x.strip().split()),subprocess.getoutput(cmd).splitlines()) df = pd.DataFrame(data,columns=["hhat","xsec"]) df = df.sort_values(by=["hhat"]) df["xsec"] *= 1e3 return df def plot_custom(): df13 = get_df("out_test_13tevhhatscan_part") fig,ax = plt.subplots() hhats = np.linspace(0.,0.20,100) ax.plot(df13.hhat,df13.xsec/df13.xsec.min(),marker="o",label="MadGraph",markersize=5.,alpha=1.,color="C2") from scipy.optimize import curve_fit def f(x,a,b,c): return 1.+a*x+b*x**2+c*x**3 subset = df13.hhat.values<0.25 coef,cov = curve_fit(f,df13.hhat.values[subset],(df13.xsec/df13.xsec.min()).values[subset]) coef = np.concatenate([np.array([1.]),coef])[::-1] xs = np.linspace(0.,0.25,1000) fpoly = np.poly1d(coef) ys = fpoly(xs) label = ( r"Fit to MadGraph: " r"${:.0f}" r"{:+.2f}\hat{{H}}" r"{:+.2f}\hat{{H}}^2" r"{:+.2f}\hat{{H}}^3$" ).format(*coef[::-1]) ax.plot(xs,ys,color="k",label=label) # ul = BDTOBSUL/11.97 # dfy, fyint = get_corrected_ul() # ax.plot(hhats,np.ones(len(hhats))*ul,label="uncorrected obs UL (BDT)",color="0.6",linestyle="--") # ax.plot(hhats,fyint(hhats)/11.97,label="ttH-corrected obs UL (BDT)",color="k",linestyle="--") # dfcustom["xsecratio"] = fpoly(dfcustom.hhat)*dfcustom.obsr # ax.plot(dfcustom["hhat"],dfcustom["xsecratio"],label="Dedicated samples: obs UL (BDT)",color="r",marker="x") # fcustomint = interpolate.interp1d(dfcustom["hhat"],dfcustom["xsecratio"],kind="linear") # xs = np.linspace(dfcustom.hhat.min(),dfcustom.hhat.max(),100) # xs = np.linspace(0.,dfcustom["hhat"].max(),1000) # xy = np.c_[xs,fpoly(xs),fyint(xs)/11.97,fcustomint(xs)] # xcross = xy[np.abs(xy[:,1]-xy[:,3]).argmin()][0] # ax.plot([xcross,xcross],[1.,ul*1.5],linewidth=1.0,color="r",linestyle="--") # ax.annotate( # "$\hat{{H}}={:.3f}$".format(xcross), # color="r", # xy=(xcross,1.0), # xytext=(xcross*1.2,1+(ul-1)*0.5), # arrowprops=dict(arrowstyle="->",color="r"), # ha="left", # fontsize=12 # ) ax.set_ylim([1.,ax.get_ylim()[1]]) ax.set_ylabel(r"$\sigma_{\hat{H}+\mathrm{SM}}/\sigma_\mathrm{SM}$") ax.set_title(r"$\sigma_{\hat{H}+\mathrm{SM}}/\sigma_\mathrm{SM}$ vs $\hat{H}$", fontsize=14) ax.set_xlabel(r"$\hat{H}$") ax.text(0.01, 2.75, "MadGraph5\n13TeV", fontsize=12) ax.yaxis.set_minor_locator(MultipleLocator(0.1)) ax.legend() fig.set_tight_layout(True) fig.savefig("higgs_oblique.pdf") os.system("ic higgs_oblique.pdf") if __name__ == "__main__": plot_custom() <file_sep>#!/usr/bin/env sh mv Figure_001-a.pdf diag_T1tttt.pdf mv Figure_001-b.pdf diag_T5ttbbWW.pdf mv Figure_001-c.pdf diag_T5tttt.pdf mv Figure_001-d.pdf diag_T5ttcc.pdf mv Figure_001-e.pdf diag_T5qqqqWZ.pdf mv Figure_002-a.pdf diag_T6ttWW.pdf mv Figure_002-b.pdf diag_T6ttHZ.pdf mv Figure_003-a.pdf diag_T1qqqqL.pdf mv Figure_003-b.pdf diag_T1tbs.pdf mv Figure_004-a.pdf br_ht.pdf mv Figure_004-b.pdf br_met.pdf mv Figure_004-c.pdf br_mtmin.pdf mv Figure_004-d.pdf br_njets.pdf mv Figure_004-e.pdf br_nbtags.pdf mv Figure_004-f.pdf br_charge.pdf mv Figure_005-a.pdf SRHH_TOTAL.pdf mv Figure_005-b.pdf SRHL_TOTAL.pdf mv Figure_005-c.pdf SRLL_TOTAL.pdf mv Figure_006-a.pdf SRLM_TOTAL.pdf mv Figure_006-b.pdf SRMLONZ_TOTAL.pdf mv Figure_006-c.pdf SRMLOFFZ_TOTAL.pdf mv Figure_007-a.pdf scan_t1tttt.pdf mv Figure_007-b.pdf scan_t1ttbb.pdf mv Figure_007-c.pdf scan_t5tttt.pdf mv Figure_007-d.pdf scan_t5ttcc.pdf mv Figure_008-a.pdf scan_t5qqqqvv.pdf mv Figure_008-b.pdf scan_t5qqqqvvdm20.pdf mv Figure_009-a.pdf scan_t5qqqqww.pdf mv Figure_009-b.pdf scan_t5qqqqwwdm20.pdf mv Figure_010-a.pdf scan_t6ttww.pdf mv Figure_011-a.pdf scan_t6tthzbrh.pdf mv Figure_011-b.pdf scan_t6tthzbrb.pdf mv Figure_011-c.pdf scan_t6tthzbrz.pdf mv Figure_012-a.pdf scan_rpv_t1qqqql.pdf mv Figure_012-b.pdf scan_rpv_t1tbs.pdf mv Figure_013-a.pdf scan_milimits_met.pdf mv Figure_013-b.pdf scan_milimits_ht.pdf
8f8b24714c27b2785bc4b66604feb66a47ec2b1f
[ "Markdown", "Python", "Makefile", "Shell" ]
13
Python
aminnj/notmythesis
1ad00aa07e7b5b37a3eea60cf5206e85fafd43fb
4413c468135216922136e2c1edbd172c8dde69cb
refs/heads/master
<repo_name>Ziyu-Chen/image_hashing<file_sep>/download_image.py import requests from PIL import Image from choose_headers_randomly import choose_headers_randomly directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/' def download_image(url): image_path = directory_path # Generate the correct image type according to the given URL if url.endswith('.jpg'): image_path += 'temp.jpg' elif url.endswith('.png'): image_path += 'temp.png' elif url.endswith('.webp'): image_path += 'temp.webp' else: image_path += 'temp.jpg' # Save the image response = requests.get(url, stream=True, headers=choose_headers_randomly()) if response.status_code == 200: with open(image_path, 'wb') as f: f.write(response.content) # Convert the image if its type is webp. if image_path.endswith('.webp'): img = Image.open(image_path).convert('RGB') image_path = image_path.replace('.webp', '.jpg') img.save(image_path, 'jpeg') return image_path <file_sep>/maxmara_enforcement_document.py from collections import defaultdict import os import pandas as pd enforcement_document_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara/enforcement_document.csv' comparison_directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara/comparison/' listings_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara/taobao_store_seller/bulk_upload_data.xlsx' new_bulk_upload_data_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara/taobao_store_seller/new_bulk_upload_data.xlsx' image_urls_paths = [ '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara_image_urls/weekendmaxmara.csv', '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/maxmara_image_urls/weekendmaxmara2.csv' ] language = 'CN' listings = pd.read_excel(listings_path) selector = [False for _ in range(len(listings))] enforcement_document_dict = defaultdict(list) image_urls = pd.concat([pd.read_csv(image_urls_path) for image_urls_path in image_urls_paths]) for _, _, file_names in os.walk(comparison_directory_path): for file_name in file_names: first_hyphen_position = file_name.index('-') listing_index = file_name[:first_hyphen_position] image_name = file_name[first_hyphen_position+1:] listing_url = None image_url = None image_source = None for i in range(len(listings)): if listing_index == str(listings.iloc[i]['Item ID (Required|Non-editable)']): selector[i] = True listing_url = listings.iloc[i]['URL (Required)'] break for i in range(len(image_urls)): url = image_urls.iloc[i]['url'] source = image_urls.iloc[i]['source'] if image_name in url: image_url = url image_source = source break if language == 'EN': enforcement_document_dict['listing_url'].append(listing_url) enforcement_document_dict['image_url'].append(image_url) enforcement_document_dict['image_source'].append(image_source) elif language == 'CN': enforcement_document_dict['商品链接'].append(listing_url) enforcement_document_dict['图片链接'].append(image_url) enforcement_document_dict['图片来源'].append(image_source) pd.DataFrame(enforcement_document_dict).to_csv(enforcement_document_path, encoding='utf-8') listings[selector].to_excel(new_bulk_upload_data_path)<file_sep>/lego_image_hashes.py import imagehash import pandas as pd import os from PIL import Image from collections import defaultdict from square_crop import square_crop directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego_images/' data_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/image_hashes_2.csv' data_dict = defaultdict(list) for image_name in os.listdir(directory_path): image_path = directory_path + image_name with Image.open(image_path) as image: image = square_crop(image) ahash = imagehash.average_hash(image) dhash = imagehash.dhash(image) phash = imagehash.phash(image) whash = imagehash.whash(image) data_dict['image_name'].append(image_name) data_dict['ahash'].append(ahash) data_dict['dhash'].append(dhash) data_dict['phash'].append(phash) data_dict['whash'].append(whash) print('Finished No. %s' % image_name) data = pd.DataFrame(data_dict) data.to_csv(data_path)<file_sep>/index.py import imagehash import pandas as pd from PIL import Image from download_image import download_image data_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/panasonic/panasonic_blue_colored.csv' data = pd.read_csv(data_path) for i in range(len(data)): image_url = data.iloc[i]['Thumbnail Url'] image_path = download_image(image_url) image = Image.open(image_path) ahash = imagehash.average_hash(image) dhash = imagehash.dhash(image) phash = imagehash.phash(image) whash = imagehash.whash(image) data.at[i, 'ahash'] = ahash data.at[i, 'dhash'] = dhash data.at[i, 'phash'] = phash data.at[i, 'whash'] = whash print('Finished No. %d' % i) data.to_csv(data_path)<file_sep>/lego_listings.py import imagehash import pandas as pd import os from PIL import Image from collections import defaultdict from download_image import download_image from square_crop import square_crop listings_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/listings.csv' image_hashes_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/image_hashes2.csv' lego_images_directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego_images/' comparison_directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/comparison2/' listings = pd.read_csv(listings_path) images = pd.read_csv(image_hashes_path) def hamming_distance(chaine1, chaine2): return sum(c1 != c2 for c1, c2 in zip(chaine1, chaine2)) def find_closest_images(hash, hash_type='phash'): h = str(hash) distance_to_image_name = defaultdict(list) distance = float('inf') for i in range(len(images)): current_distance = hamming_distance(h, images.iloc[i][hash_type]) image_name = images.iloc[i]['image_name'] distance_to_image_name[current_distance].append(image_name) if current_distance < distance: distance = current_distance image_names = distance_to_image_name[distance] return (image_names, distance) def v_merge(image_paths, new_image_path, height=500): total_width = 0 for image_path in image_paths: image = Image.open(image_path) width, h = image.size total_width += int((width / h) * height) new_image = Image.new('RGB', (total_width, height)) start_width = 0 for image_path in image_paths: image = Image.open(image_path) width, h = image.size width = int((width / h) * height) image = image.resize((width, height)) new_image.paste(image, (start_width, 0, start_width + width, height)) start_width += width new_image.save(new_image_path) # for i in range(64): # os.makedirs('/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/comparison2/%d/' % (i)) for i in range(len(listings)): try: image_path = download_image(listings.iloc[i]['Thumbnail']) index = listings.iloc[i]['Item ID'] image = Image.open(image_path) image = square_crop(image) phash = imagehash.phash(image) closest_image_names, minimum_distance = find_closest_images(phash) for closest_image_name in closest_image_names: v_merge([lego_images_directory_path + closest_image_name, image_path], comparison_directory_path + '%d/%s-%s' % (minimum_distance, str(index), closest_image_name)) print(minimum_distance) print('Finished No. %d' % i) except Exception: continue<file_sep>/square_crop.py def square_crop(image): width, height = image.size half_width, half_height = int(width/2), int(height/2) cropped_image = None if width > height: area = (half_width-half_height, 0, half_width+half_height, height) cropped_image = image.crop(area) else: area = (0, half_height-half_width, width, half_height+half_width) cropped_image = image.crop(area) return cropped_image <file_sep>/README.md # image_hashing A repository for image hashing practices <file_sep>/panasonic.py import imagehash import pandas as pd import os from PIL import Image from collections import defaultdict from download_image import download_image from square_crop import square_crop listings_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/panasonic/panasonic_all_colored.csv' image_hashes_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/panasonic/panasonic_blue_colored.csv' listings = pd.read_csv(listings_path) images = pd.read_csv(image_hashes_path) def hamming_distance(chaine1, chaine2): return sum(c1 != c2 for c1, c2 in zip(chaine1, chaine2)) def find_smallest_distance(max_pct_r, max_pct_g, max_pct_b, phash): smallest_distance = 1000000 for i in range(len(images)): if abs(max_pct_r-images.iloc[i]['max_pct_r']) <= 10 and abs(max_pct_g-images.iloc[i]['max_pct_g']) <= 10 and abs(max_pct_b-images.iloc[i]['max_pct_b']) <= 10: distance = hamming_distance(phash, images.iloc[i]['phash']) if distance < smallest_distance: smallest_distance = distance return smallest_distance for i in range(len(listings)): smallest_distance = find_smallest_distance(listings.iloc[i]['max_pct_r'], listings.iloc[i]['max_pct_g'], listings.iloc[i]['max_pct_b'], listings.iloc[i]['phash']) listings.at[i, 'smallest_distance'] = smallest_distance print(smallest_distance) print('Finished No. %d' % i) listings = listings.sort_values(by=['smallest_distance']) listings.to_csv('/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/panasonic/panasonic_all_colored.csv')
1ab2c3dbe3b8323c9167236160af263daca0ec5d
[ "Markdown", "Python" ]
8
Python
Ziyu-Chen/image_hashing
d48443b59959f2f785b864908e9b0979de59fe7a
d2a79ff610bf5bdfb35a451a05d99bdf95bb64ec
refs/heads/main
<repo_name>hopcolony/flutter-hopcolony<file_sep>/test.sh project=${1:-} root=$PWD if [ -z "$project" ] then cd $root/packages/hop_init && flutter test cd $root/packages/hop_drive && flutter test cd $root/packages/hop_doc && flutter test cd $root/packages/hop_auth && flutter test cd $root/packages/hop_topic && flutter test else cd $root/packages/$project && flutter test fi<file_sep>/README.md <p align="center"> <a href="https://hopcolony.io"><img src="https://github.com/hopcolony/hopcolony/raw/master/docs/assets/images/logo.png" alt="hopcolony"></a> </p> <p align="center"> <em>Focus on you app. Let us manage your backend.</em> </p> |[![pub package](https://github.com/hopcolony/flutter-hopcolony/workflows/HopAuth/badge.svg)](https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopAuth)|[![pub package](https://github.com/hopcolony/flutter-hopcolony/workflows/HopDoc/badge.svg)](https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopDoc)|[![pub package](https://github.com/hopcolony/flutter-hopcolony/workflows/HopDrive/badge.svg)](https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopDrive)|[![pub package](https://github.com/hopcolony/flutter-hopcolony/workflows/HopInit/badge.svg)](https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopInit)|[![pub package](https://github.com/hopcolony/flutter-hopcolony/workflows/HopTopic/badge.svg)](https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopTopic)| |---|---|---|---|---| |[![pub package](https://img.shields.io/pub/v/hop_auth.svg)](https://pub.dev/packages/hop_auth)|[![pub package](https://img.shields.io/pub/v/hop_doc.svg)](https://pub.dev/packages/hop_doc)|[![pub package](https://img.shields.io/pub/v/hop_drive.svg)](https://pub.dev/packages/hop_drive)|[![pub package](https://img.shields.io/pub/v/hop_init.svg)](https://pub.dev/packages/hop_init)|[![pub package](https://img.shields.io/pub/v/hop_topic.svg)](https://pub.dev/packages/hop_topic)| --- **Documentation**: <a href="https://hopcolony.io/latest/docs" target="_blank">https://hopcolony.io/latest/docs</a><file_sep>/packages/hop_topic/CHANGELOG.md ## 0.0.1 * Generic Implementation ## 0.0.2 * AMQP and STOMP implementation depending on platform ## 0.0.3 * Updated Dependencies ## 0.0.4 * Fixed issue on stomp on connect ## 0.0.5 * Added dart_amqp as an internal dependency. Credits to https://github.com/achilleasa/dart_amqp ## 0.0.6 * Added null-safety * Updated tests to wait for subscription message to arrive<file_sep>/packages/hop_auth/README.md <p align="center"> <a href="https://hopcolony.io"><img src="https://github.com/hopcolony/hopcolony/raw/master/docs/assets/images/logo.png" alt="hopcolony"></a> </p> <p align="center"> <em>Focus on you app. Let us manage your backend.</em> </p> <p align="center"> <a href="https://github.com/hopcolony/flutter-hopcolony/actions?query=workflow%3AHopAuth" target="_blank"> <img src="https://github.com/hopcolony/flutter-hopcolony/workflows/HopAuth/badge.svg" alt="Test"> </a> </a> <a href="https://pub.dev/packages/hop_auth" target="_blank"> <img src="https://img.shields.io/pub/v/hop_auth.svg" alt="Package version"> </a> </p> --- **Documentation**: <a href="https://hopcolony.io/latest/docs" target="_blank">https://hopcolony.io/latest/docs</a> **Source Code**: <a href="https://github.com/hopcolony/flutter-hopcolony/packages/hop_auth" target="_blank">https://github.com/hopcolony/flutter-hopcolony/packages/hop_auth</a><file_sep>/packages/hop_topic/example/README.md # Hop Colony Topics<file_sep>/packages/hop_init/CHANGELOG.md ## 0.0.1 * Initial functionality ## 0.0.2 * Improved config management ## 0.0.3 * Updated internal dependencies ## 0.0.4 * Added null-safety<file_sep>/packages/hop_auth/CHANGELOG.md ## 0.0.1 * Initial Implementation ## 0.0.2 * Refactored code ## 0.0.3 * Added signOut method * Added authChangeStream to listen to auth changes * Added authChangeWidget to easily create Widgets depending on the current user changes in real time * Updated the example ## 0.0.4 * Updated dependencies ## 0.0.5 * Updated hop_topic dependency ## 0.0.6 * Added signInWithEmailAndPassword * Added HopAuth.instance.ready ## 0.0.7 * Added null-safety ## 0.0.8 * Refactored signInWithHopcolony to match OAuth server ## 0.0.9 * Fixed issue with null-safety on authChangeStream ## 0.0.10 * Handling hopcolony sign-in in this package * Exporting HopAuthProvider ## 0.1.0 * signInWithHopcolony works with OAuth ~~~~~~~~~NOT PUBLISHED<file_sep>/packages/hop_doc/example/README.md # Tripel Doc Example<file_sep>/packages/hop_doc/CHANGELOG.md ## 0.0.1 * Initial Implementation ## 0.0.2 * Refactored and added test suite ## 0.0.3 * Added getWidget to IndexReference and DocumentReference to build Widgets easier depending on the status of the request * Changed dio for http ## 0.0.4 * Added null-safety ## 0.0.5 * Added Token to header<file_sep>/packages/hop_drive/CHANGELOG.md ## 0.0.1 * Initial Implementation ## 0.0.2 * Refactored and added test suite ## 0.0.3 * Changed dio for http ## 0.0.4 * Added null-safety
6f5f1bc42aa8a610257f32779302ebbafe5abe2b
[ "Markdown", "Shell" ]
10
Shell
hopcolony/flutter-hopcolony
7b00bc107d83126b56f2c8f93a3b189f232c38c7
c62a89bd2d7011a0ee387e315ae2c0fe24af7d86
refs/heads/master
<file_sep>""" // Time Complexity : O(n), length of T // Space Complexity : O(1), max 26 // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no """ from collections import defaultdict class Solution(object): def customSortString(self, S, T): """ :type S: str :type T: str :rtype: str """ dict = defaultdict(int)# for storing chars in T and their frequencies res = "" for i in T: dict[i] += 1 for i in S: #for chars present in S in order, keep adding to result and then remove them from the dictionary res = res + i*dict[i] dict.pop(i) for k,v in dict.items(): #add remaining chars to res in any order res = res + k*v return res<file_sep>""" // Time Complexity : O(n), // Space Complexity : O(1), max 26 // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no """ from collections import defaultdict class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = defaultdict(int) #to store index slow = fast = 0 maxval = 0 while fast < len(s): ch = s[fast] if ch in d: slow = max(slow, d[ch]) #will update slow if theres a repeat d[ch] = fast + 1 maxval = max(maxval, fast - slow + 1) #keep track of max length fast += 1 return maxval
64580c64ea202ae230028f96a832920b2e0d50c1
[ "Python" ]
2
Python
akshatasawhney/Strings-1
90e9b51f6652549316499c24b7ca3089982bd602
cbe14b0373106d4c443fcb8dd6f4e61c5a815bf9
refs/heads/master
<file_sep>const shoppingLists_view = ((data) =>{ let html =` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="style.css"> <link rel="shortcut icon" href="https://icons.iconarchive.com/icons/iconsmind/outline/512/Shopping-Cart-icon.png"/> <title>Shopping lists</title> </head> <body> <div class="full"> Logged in as user: ${data.user_name} <form action="/logout" method="POST"> <button type="submit">Log out</button> </form> <div class="middle"> <form action="/add-shopping-list" method="POST"> <input type="text" name="list_name" placeholder="name of list"> <button type="submit">Add shopping list</button> </form>`; data.shoppingLists.forEach((shoppingList) => { html += ` <hr> <div> <a href="/shoppinglist/${shoppingList.name}?id=${shoppingList._id}">${shoppingList.name}</a> <form action="/delete-shopping-list" method="POST"> <input type="hidden" name="list_id", value="${shoppingList._id}"> <button type="submit" class="delete_button">Delete shopping list</button> </form> </div>`; }); html += ` </div> </div> </body> </html>`; return html; }); const shoppingList_view = ((data) => { let html =` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../style.css"> <link rel="shortcut icon" href="https://icons.iconarchive.com/icons/iconsmind/outline/512/Shopping-Cart-icon.png"/> <title>Shopping list: ${data.shopping_list_name}</title> </head> <body> <div class="full"> <a href="/">Back to shopping lists view</a> <div class="middle"> <h3>Your shopping list: ${data.shopping_list_name}</h3> <form action="/add-product" method="POST" id="add-product"> <p>Fill below to add new poduct on your list</p> <table> <tr> <th><label for="pname">Product name:</label></th> <th><label for="pquantity">Quantity:</label></th> <th><label for="purl">Url for image:</label></th> </tr> <tr> <td><input type="text" name="product_name" id="pname" placeholder="name of product"></td> <td><input type="number" class="quantity" name="quantity" id="pquantity" min="1" value="1"></td> <td><input type="text" name="product_image" id="purl" placeholder="url for image"></td> <input type="hidden" name="list_id", value="${data.shoppingList_id}"> <td><button type="submit">Add product to list</button></td> </tr> </table> </form>`; if (data.products.length != 0){ html += ` <h4>Products on your shopping list:</h4> <table> <thead> <tr> <th>Product</th> <th>Image</th> <th>Count</th> <th>Delete</th> </tr> </thead> `; data.products.forEach((product) => { html += ` <tbody> <tr> <th>${product.name}</th> <td><img src="${product.image}" width="100"></img></td> <td> <form action="/shoppinglist/${data.shopping_list_name}?id=${data.shoppingList_id}" method="POST"> <input type="number" class="quantity" name="quantity" min="1" value="${product.quantity}"> <br> <input type="hidden" name="product_id", value="${product._id}"> <button type="submit">Update</button> </form> </td> <td> <form action="/delete-product" method="POST"> <input type="hidden" name="product_id", value="${product._id}"> <input type="hidden" name="list_id", value="${data.shoppingList_id}"> <button type="submit" class="delete_button">Delete product</button> </form> </td> </tr> </tbody>`; }); html += `</table>`; } else{ html += ` <p>You not have any products on your list yet</p> `; } html += ` </div> </div> </body> </html> `; return html; }); module.exports.shoppingLists_view = shoppingLists_view; module.exports.shoppingList_view = shoppingList_view;<file_sep>const express = require('express'); const PORT = process.env.PORT || 8080; const body_parser = require('body-parser'); const session = require('express-session'); const mongoose = require('mongoose'); //Controllers const auth_controller = require('./controllers/auth-controllers'); const shoppingList_controller = require('./controllers/shoppingList-controllers') let app = express(); app.use(body_parser.urlencoded({ extended: true })); //Serve static files app.use(express.static('public')); app.use(session({ secret: '1234qwerty', resave: true, saveUninitialized: true, cookie:{ maxAge: 1000000 } })); const is_logged_handler = (req, res, next) => { if(!req.session.user){ return res.redirect('/'); } next(); }; //Auth app.use(auth_controller.handle_user); app.get('/', auth_controller.get_main); app.post('/login', auth_controller.post_login); app.post('/register', auth_controller.post_register); app.post('/logout', auth_controller.post_logout); //Shoppinglists app.get('/', is_logged_handler, shoppingList_controller.get_shoppingLists); app.get('/shoppingList/:name', is_logged_handler, shoppingList_controller.get_shoppingList) app.post('/add-shopping-list', is_logged_handler, shoppingList_controller.post_shoppingList); app.post('/delete-shopping-list', is_logged_handler, shoppingList_controller.post_delete_shoppingList); app.post('/add-product', is_logged_handler, shoppingList_controller.post_add_product); app.post('/shoppingList/:name', is_logged_handler, shoppingList_controller.post_update_count); app.post('/delete-product', is_logged_handler, shoppingList_controller.post_delete_product); //Not found app.use((req, res, next) => { console.log('404'); res.status(404); res.send('page not found') }); //mongodb+srv://shoppinglistdb-user:<EMAIL>/test?retryWrites=true&w=majority const mongoose_url = 'mongodb+srv://shoppinglistdb-user:HuhGj8nht8XfKqu5@cluster0-ozu87.mongodb.net/test?retryWrites=true&w=majority'; mongoose.connect(mongoose_url, { useUnifiedTopology: true, useNewUrlParser: true }).then(()=>{ console.log('Mongoose connected'); console.log('Start express server'); app.listen(PORT); });
0b75518bc98ed0b6afcf27998cb786cbf48b62a3
[ "JavaScript" ]
2
JavaScript
ohsu19mika/VEOH-ShoppingList
90aca806badf2e70a48a92d5f5fe934afc3fee39
747d15d5647f16a1639d56753fc33c0af0b7dcc1
refs/heads/master
<repo_name>MohAnghabo/pinGen<file_sep>/routes/index.js var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function (req, res, next) { let validPins = [] let unvalidPins = [] function pinChecker(pin) { let pingString = pin.toString().split(""); if (pingString.length != 4) { return false } if ((pingString[0] == pingString[1] && pingString[1] == pingString[2]) || (pingString[1] == pingString[2] && pingString[2] == pingString[3])) { return false } if ((parseInt(pingString[0]) + 1) === (parseInt(pingString[1])) && (parseInt(pingString[1]) + 1) === (parseInt(pingString[2]))) { return false } if ((parseInt(pingString[1]) + 1) === (parseInt(pingString[2])) && (parseInt(pingString[2]) + 1) === (parseInt(pingString[3]))) { return false } return true; } function pinGenerator() { let pin = []; let unvalidPin = [] for (let i = 0; i <= 9999; i++) { if (i < 10) { if (pinChecker("000" + i) == true) { pin.push("000" + i); } else { unvalidPin.push("000" + i); } } else if (i < 100) { if (pinChecker("00" + i) == true) { pin.push("00" + i); } else { unvalidPin.push("00" + i); } } else if (i < 1000) { if (pinChecker("0" + i) == true) { pin.push("0" + i); } else { unvalidPin.push("0" + i); } } else { if (pinChecker(i) == true) { pin.push(i); } else { unvalidPin.push(i); } } } return { validPins: pin, unvalidPins: unvalidPin }; } validPins = pinGenerator().validPins; let validPinsCount = validPins.length; unvalidPins = pinGenerator().unvalidPins; let unvalidPinsCount = unvalidPins.length; res.send({ validPinsCount: validPinsCount, validPins: pinGenerator().validPins, unvalidPinsCount: unvalidPinsCount, unvalidPins: pinGenerator().unvalidPins, }); }); module.exports = router;
1e124f0d5d35c9ef86bc8289751b12ef819398d8
[ "JavaScript" ]
1
JavaScript
MohAnghabo/pinGen
fa7d93f99cd5600a46ecb5db1bfd65a22d4d3bf6
28a339a1cc0020a49d57422d5939ec0420ffabc5
refs/heads/master
<repo_name>pigottlaura/SSP-Assignment-02-PortfolioBuilder<file_sep>/public/javascripts/loginScript.js jQuery(document).ready(function ($) { console.log("Login script loaded"); // Everytime the username or password field of the create account form are changed, sending AJAX requests // to the server to see if these credentials are available $("#createAccount").find("input[name='username'], input[name='portfolioURL']").change(function () { // Altering the value of these two inputs, to ensure they contain no spaces (replacing them // globally) and are in lower case $("input[name='username'], input[name='portfolioURL']").val(function () { return $(this).val().toLowerCase().replace(/ /g, ""); }); // Getting the value of the form username var formUsername = $("input[name='username']").val().toLowerCase(); // Checking if the portfolio URL is currently empty if ($("input[name='portfolioURL']").val() == "") { // Defaulting the portfolio URL to be equal to the user's username. Whether or not this url // is available or not will be checked following this $("input[name='portfolioURL']").val(formUsername.replace(/ /g, "")).removeClass("formWarning"); } // Getting the portfolio URL after the above check, as it may have changed var formPortfolioUrl = $("input[name='portfolioURL']").val().toLowerCase(); // Calling the check credentials available function from the main script file, to sending // an AJAX request to the server, and update the glyphicons beside each of the form inputs // accordinly i.e. to show if they are available or not checkCredentialsAvailable(formUsername, formPortfolioUrl, function (responseData) { if (responseData.usernameAvailable) { console.log("Username available"); $("#usernameStatusIcon").attr("class", "glyphicon glyphicon-ok-circle"); } else { console.log("Username not available"); $("#usernameStatusIcon").attr("class", "glyphicon glyphicon-ban-circle"); } if (responseData.portfolioURLAvailable) { console.log("Portfolio URL available"); $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ok-circle"); } else { console.log("Portfolio URL not available"); $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ban-circle"); } }); }); // Validating the create account form before it can be submitted to the server $("#createAccount").submit(function (event) { // Creating a boolean which will be used to determine if this form should be allowed to // submit or not. This will only be set to true if all required form fields have a value // supplied in them, and the password/confirmPassword field's values match var allowSubmit = false; // Passing this form into the checkAllFieldsSupplied method declared below. This will return // a boolean value var allRequiredFieldsSupplied = checkAllFieldsSupplied(this); // Getting the form username and portfolio url var username = $(this).find("input[name='username']").val().toLowerCase(); var portfolioURL = $(this).find("input[name='portfolioURL']").val().toLowerCase(); // If all fields required were supplied (as defined above) if (allRequiredFieldsSupplied) { console.log("All fields supplied"); // Checking that the password and confirm password fields match. Also checking this server side if ($(this).find("input[name='password']").val() == $(this).find("input[name='confirmPassword']").val()) { console.log("passwords match"); // This form is allowed to submit allowSubmit = true; } else { console.log("passwords don't match"); } } else { console.log("missing fields"); } console.log("about to return from function"); // Returning the value of allowSubmit to the function. If false, the form will not be sent to the server return allowSubmit; }); // VA $("#loginAccount").submit(function (event) { // Creating a boolean which will be used to determine if this form should be allowed to // submit or not. This will only be set to true if all required form fields have a value // supplied in them, and the password/confirmPassword field's values match var allowSubmit = false; // Passing this form into the checkAllFieldsSupplied method declared below. This will return // a boolean value var allRequiredFieldsSupplied = checkAllFieldsSupplied(this); // Getting the form username var username = $(this).find("input[name='loginUsername']").val().toLowerCase(); // If all fields required were supplied (as defined above) if (allRequiredFieldsSupplied) { console.log("All fields supplied"); allowSubmit = true; } else { console.log("missing fields"); } console.log("about to return from function"); // Returning the value of allowSubmit to the function. If false, the form will not be sent to the server return allowSubmit; }); // Removing warnings from form inputs (if they exist) when the user types into them $("form input").not("[type='submit']").keyup(function (event) { // As long as the new lenght of the input value is greater than 0 if ($(this).val().length > 0) { $(this).removeClass("formWarning"); } }); }); // Used by multiple forms to check if all their fields have been supplied. Accepts one argument, // which references the form it is about to check function checkAllFieldsSupplied(form) { // Defaulting all fields supplied to true, until proven otherwise below var allRequiredFieldsSupplied = true; console.log("About to check this form - " + $(form).attr("id")); // Checking all input fields within this form, to ensure that none are left empty. // Excluding the submit input from this search, as this cannot take a user defined // value. $(form).find("input").not("[type='submit']").each(function (index, element) { // If this input value is empty if ($(element).val() == "") { // All required fields is now false allRequiredFieldsSupplied = false; // Adding a warning class to any fields that are empty $(element).addClass("formWarning"); } else { // This input has a value. Removing the form warnin class (if it exists on the element) $(element).removeClass("formWarning"); } }); console.log("allRequiredFieldsSupplied = " + allRequiredFieldsSupplied); // Returning the boolean value which represents whether or not all form fields contained a value return allRequiredFieldsSupplied; }<file_sep>/custom_modules/googlePassport.js // Requiring my custom module (databaseModels) which returns an object which // contains all of the models (document templates) for the database, so that // I can then access the relevant models within this module var databaseModels = require("../custom_modules/databaseModels"); // Accessing the User and Portfolio models, from the custom databaseModels module above, // so that I can use them to query, add, update and remove documents from their collections // within the MongoDB database var User = databaseModels.User; var Portfolio = databaseModels.Portfolio; // Requiring the passport module, so that I can set up passport middleware, including // the Google OAuth2 one below, to allow for alternative methods of creating/logging in // to accounts on this app var passport = require('passport'); // Accessing the OAuth2Strategy object from the passport-google-oath exports object, // so that I can set up Google authorisation functionality, so that users can login/create // an account on this app using their Google account. var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; // Setting up the credentials for requesting authorisation from users Google accounts for // this app. Passing in a new Google strategy, which contains the client ID and client // secret keys I have generated on my Google developer console, so that this app will // be recognises, and authorised to make these requests (storing this values in environment // variable in my .vscode/launch.json file, as well as in environment variables on the Azure // server, for security purposes). Specifying the callback URL i.e. where the user should // be redirected to once they have authorised this app to access our account. This URL will // send the user into the authentication route of this app, so that they can be authorised // to access the admin section in the same way as all other users for the app (although their // User document will have slightly different properties, as they will have a googleID etc) passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: "/admin/authentication/google/callback" }, function (accessToken, refreshToken, profile, done) { // Setting up the callback function for when a user returns from authorising the app through Google // Checking to see if this user already exists i.e. if they have already created an account // on this app using this Google account User.findOne({ googleId: profile.id }, {}, function (err, user) { if (err) { console.log("GOOGLE - Cannot check if this Google users already exists - " + err); // Returning the error to the function(as specified in the passport API) return done(err); } else { // Checking if any users were returned form this query i.e. if the user already exists if (user == null) { console.log("GOOGLE - " + profile.name.givenName + " " + profile.name.familyName + " is a new user"); // Creating a new user document, based on the user model (sourced from the exports // of the databaseModels module) var newUser = new User({ firstName: profile.name.givenName, lastName: profile.name.familyName, googleId: profile.id, profilePicture: profile._json.image.url }); // Saving the new user to the database newUser.save(function (err, newUser) { if (err) { console.log("GOOGLE - Could not save new user to the database - " + err); // Returning the error to the function(as specified in the passport API) return done(err); } else { console.log("GOOGLE - New user successfully saved to the database"); // Creating a new portfolio for the user, based on the portfolio model. // The reason I am waiting until this point to create the portfolio, is that if // there is any reason why a user cannot be created i.e. due to a missing field etc, // then I don't want to create a new portfolio, as without an owner id it would be useless var newPortfolio = new Portfolio({ owner: newUser._id, portfolioURL: "GoogleUser-" + profile.id, pages: { contact: { contactDetails: { name: profile.name.givenName + " " + profile.name.familyName, email: profile.emails[0].value } } } }) ; // Saving the new portfolio to the database newPortfolio.save(function (err, newPortfolio) { if (err) { console.log("GOOGLE - Could not save new portfolio to the database - " + err); } else { console.log("GOOGLE - New portfolio successfully saved to the database"); // Returning no error, along with the newUser to the function(as specified in the passport API) return done(null, newUser); } }); } }); } else { // This user already exists in the database, and hence is a returning user console.log("GOOGLE - " + profile.name.givenName + " " + profile.name.familyName + " is an existing user"); // Returning no error, along with the existing user to the function(as specified in the passport API) return done(null, user); } } }); } )); // Exporting the passport object, so that it can be required from other routes when needed // i.e. in the authentication.js route module.exports = passport;<file_sep>/README.md # Portfolio Builder ## Log in and create an online portfolio in minutes Assignment-02 for the Server Side Programming module, as part of the Creative Multimedia B.Sc. (hons) degree course in Limerick Institute of Technology, Clonmel. Available on: http://portfolio-builder.herokuapp.com ### Project Specifications - Languages - NodeJS - JavaScript - JADE - HTML - CSS - Libraries - jQuery - jQuery UI - Lightbox - Bootstrap - Modules (not including their dependencies) - express - express-session - connect-mongo - mongoose - multer - passport - passport-google-oauth - jade ### Project Structure - App structure - Basis of app created using express-generator - Basis of website layout completed using a Bootstrap grid system, along with jQuery UI for functionalities - Database - All users, portfolios and media items are stored in a Mongo database (generated and run using the Mongoose module) - The database connection is shared among multiple routes through a custom module (see database.js) - Running both a local database (for development purposes) and a MongoLabs database remotely (for use when the app is running live on Azure) - Using population (similar to an SQL table JOIN) - The Portfolio document is the main point for querying the database - Each Portfolio contains the ObjectId of the owner, and an array of ObjectId's for the MediaItems which belong to it - Each time the Portfolio model is queries, using the populate() method to source the relevant documents using their ObjectId to reference them - This appears to be much faster, and returns all the relevant data for the portfolio in one query - Database Models - User - User documents contain details such as username, password, GoogleId etc. - Portfolio - Portfolio documents contain a reference to the ObjectId of the owner (User), as well as an array of ObjectId's which reference the media items which belong to it (MediaItem) - MediaItem - MediaItem documents contain all details relating to the file (path, mime type, size etc.) as well as the index position of the media item in the portfolio, and the category in which it exists. - MediaItems also contain a reference to the ObjectId of their owner (User) - Mongoose Middleware - e.g. .pre("remove") and post("save") - Makes it possible for me to perform a cascade delete of all media items from Portfolio, before they are deleted - Each time a new media item is saved, its object id will be added to the Portfolio of its owner - If a media item is deleted, its object id will also be deleted from the Portfolio document of its owner - Created a custom sortMediaItems() function on the methods object of the Portfolio schema, which sorts the media items of the document which is passed into it and returns the result to the callback - Accounts - Users can log in to create a new portfolio using their Google account. Using the passport-google-oauth module to generate this functionality. - Users can create their own accounts on the server, by providing their own username and password, while also being able to choose their portfolio URL at signup - Any password stored in the database are encrypted using AES-256-CTR - When users are filling out the log in form, using an AJAX request to the server to check if the username and/or portfolioURL are available. Giving feedback to the user (i.e. to let them know if these credentials are available) through the use of glyphicons to the right of the relevant input fields - Sessions - Initialised sessions are initialised by express-sessions, and persisted using the connect-mongo module - The MongoStore is hosted on the same database connection as the rest of the database models - Once a user logs out, their session is removed from the store and destroyed on the server - Secure Admin Section - All requests to paths beginning with "/admin" have to pass through the custom authentication.js route - If no user session exists, then no area of the admin section can be accessed (through any HTTP request method) - Users that attempt to access the "/admin" section without being logged in will be redirected back to the home page - Media Uploads - Media files can be uploaded to the server, using the Multer module to parse the file data - Server-side, supporting multiple files in the one upload. This has been restricted to one file per upload on the client-side, due to delays incurred when the app is running on Azure - To re-enable multiple uploads, the "multiple" attribute would need to be added onto the "#uploadMedia" input element in the admin view - Filtering the media uploads - A user session has to exist when an upload occurs or the file will be rejected - Only accepting files with a mime type beginning with "image/" or "video/". Also accepting mime types of "application/x-shockwave-flash", but storing these as fileType "swf" - Media items are stored in different directories based their mime or file type i.e. images are stored in the public 'media_uploads/images' directory etc. - Dynamic Pages - No HTML is stored on the server - All pages are generated dynamically using the Jade template engine - Data is sourced from the relevant portfolio, and rendered using the appropriate views i.e. portfolio.jade - Portfolio pages - Rows of user images are displayed using a grid system - Images are clickable/expandable through the use of LightBox2. Currently only images are viewable in this format - All images can be scrolled through from within the one lightbox session - All media items can be filtered by category (if the owner has assigned categories to the media items) - There are two "pages" on a portfolio site - "Home" and "Contact" - Admin page - Displaying the user's Google profile picture, or default profile picture - Allowing the user to upload media items, with the option to give them a title - Media items can be reordered by dragging and dropping them around in the admin panel. Each time the media items order changes, an AJAX request is sent to the server to store their new index positions - Media item titles can be updated directly on the figcaptions, and through AJAX request to the server, will be updated as soon as the title loses the focus of the user - Media items can be deleted by clicking the trash icon which appears in their top right corner - Categories can be created through the admin panel, and can then be assigned to media items through the select elements which exist at the top of each figure - Custom Portfolio URLS - Users can change their portfolio URL at any time - Accounts created though Google authentication are assigned default URLs to begin with, while users that create account on the server can specify their URL before creating their account - Icons in the input field/s inform the user if the request URL is available or not (see AJAX below) - AJAX Requests - My main aim was to reduce the number of times a user's admin panel would need to be reloaded during a session - To try and reduce the wait time for users - To reduce the load on the server - To ensure that the admin panel, and the final portfolio, are kept in sync with one another. i.e. when a change is made in the admin panel, it will be available the next time someone loads the user's portfolio - no need to instruct the app to save or update the site - When creating an account, or customising a portfolio URL, AJAX requests are sent to the server to see if the username and/or URL are available - If these login credentials are not available (i.e. they have already been taken by someone else) the user will not be allowed to submit the form to the server - When a media item's title is updated (in the Admin panel) an AJAX request is sent to the server to update that media item in the database - When media items are re-ordered (in the Admin panel) an AJAX request is sent to the server with the index position and media id of all elements involved, so that their documents can be updated - Form Validation - All forms are validated before they are allowed to submit to the server - File upload forms have to contain at least one file - Create account / login forms require all their fields to be provided before they can be submitted - Highlighting required fields in red, if a user tries to submit without providing the appropriate data - Client Side JavaScript - script.js - Included in every page of the app - Each time a jQuery .tabs() interface element is activated (i.e. a user switches tabs) finding the appropriate cookie on the document cookie object, and stores the relevant index value of this tab, so if the page is refreshed, the user will be returned to the same tabs they were on - Contains global functions such as - checkCredentialsAvailable(username, url, cb) - Sends AJAX request to the server to check if credentials are available - Returns the JSON data from the server to the caller using the callback parameter - getCookieData(findCookie) - Takes in the name of a cookie - Locates it on the document cookie object - Returns whether or not the cookie already exists, as well as its current value - resizeFigures() - Called every time the page is reloaded, resized or new elements are added - In order to ensure all objects, videos and images are the same size, using this method to resize all figures based on the largest figure on screen - If a media item's title becomes longer than one line, then all figures will resize to accommodate this - loginScript.js - Handles form validation for user's login or creating accounts - adminScript.js - Required for the admin page when a user is logged in - Handles the majority of AJAX request to the server (excluding the checking if credentials are available, as this is handled in the main script.js file) - Deals with form validation for the admin page - portfolioScript.js - Required for the public portfolio page of any user - Contains the functionality for showing/hiding media items when a user filters them by category - Custom Modules - checkDirectories - An array of directory paths can be passed to this custom module, to check if they exist and create them if they do not. Utilises the file system module. - databaseModels - An object which contains all of the database models for the app i.e. User and Media items, so that they can be used for querying, adding, deleting and updating users throughout routes. - googlePassport - This module generates the basic setup for implementing Google passport, such as setting up the passport strategy (using keys generated from my Google Developer account - stored in environment variables for security purposes), the function called to authenticate a user's login with Google (once the callback has been received by the server). This function is triggered in the authentication.js route. - cryptoEncryption - An object containing two functions, one to encrypt text, and one to decrypt it. Using sample code from https://github.com/chris-rock/node-crypto-examples/blob/master/crypto-ctr.js as the basis of the encryption with Node.js's built in Crypto module. - database.js - The exports of the module contains the connection to the mongo database, which is set up and connected within this module. The purpose of this module is to allow multiple routes of the app to share the one database connection - Mobile Responsiveness - This application scales to suit the screen dimensions of the device it is displayed on <file_sep>/custom_modules/databaseModels.js // Requiring the mongoose module, so that I can begin setting up templates // for the documents which will be stored in this database i.e. Users, Portfolios // and MediaItems var mongoose = require("mongoose"); // Requiring the Schema constructor from the mongoose object, so that I can create // custom schemas for each of the models in the database. Originally I declared these // schemas withing the .model() method, but I found that by creating them seperately first, // I could then add middleware to them, which could be shared with all instances of that // schema i.e. using a .post() middleware on the MediaItemSchema, so that every time a media // item is saved to the database, it's id will also be added to the owners portfolio document var Schema = mongoose.Schema; // Creating the users schema, from which all users documents will be based upon. Not all users // will have all of these properties (i.e. google logins will not result in a username and password, // but in a google id). var UserSchema = new Schema({ username: String, password: <PASSWORD>, googleId: String, firstName: { type: String, required: true }, lastName: { type: String, required: true }, profilePicture: { type: String, default: "../images/profilePicture.jpg" }, dateJoined: { type: Date, default: Date.now } }); // Creating the portfolio schema, from which all portfolio documents will be based upon. The purpose of // this schema is to provide a link between users and media items. The id of the owner, and any media // items they have, will be stored within instances of this document as ObjectId's. When retrieving a portfolio // from the database, I call the .populate() method of mongoose as part of the query, so that all object id's // which reference other documents will also be returned in the result (much like an SQL table JOIN) var PortfolioSchema = new Schema({ owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, portfolioURL: String, pages: { home: { mediaItems: [ { type: mongoose.Schema.Types.ObjectId, ref: 'MediaItem' } ], categories: [String] }, contact: { picture: String, info: String, contactDetails: { name: String, email: String, phone: String } } } }); // Adding a function to the methods object of the Portfolio schema, so that all instances // of models of this schema can call the sortMediaItems method upon themselves, and have the // contents of their media items sorted first by indexPosition, and then by the date/time they // were uploaded (i.e. so that the specified order of the owner is reflected, and newer items // appear first by default) PortfolioSchema.methods.sortMediaItems = function (cb) { // Calling the JS sort() method on the media items of the portfolio document which called the // method. Passing in a custom sort function, which takes in a and b i.e. will take in two // media items at a time, to determine which way to move them in the array (based on the result // returned) this.pages.home.mediaItems.sort(function (a, b) { // Creating a temporary variable to store the value that will be returned from this method. // This will either be 0 (no change), -1 (move back) or 1 (move forward) var returnVal = 0; if (a.indexPosition > b.indexPosition) { // If the indexPostion of the first media item, is greater than the index position of the second // media item, then the first media item needs to move forward returnVal = 1; } else if (a.indexPosition < b.indexPosition) { // Else if the index position of the first media item is less than the index position of the second // media item, then the first media item needs to move backward returnVal = -1; } else { // Otherwise, these two media items have the same index position, and so we will need to look at their // upload dates to decided which (if any) way they need to be sorted. NOTE - It would not be uncommon // for multiple media items to have the same index position, but it would usually only be "0", as when // media items are uploaded, this is their default, and if the user doesn't sort the media items between // uploads, then there may be multiple items with the same index. if (a.uploadedAt > b.uploadedAt) { // If the upload date of the first item is greater than the upload date of the second item, then the first // item is newer and hence should be moved backward returnVal = -1; } else if (a.uploadedAt < b.uploadedAt) { // Else if the upload date of the first item is less than the upload date of the second item, then the second // item is newer, and the first one needs to move forward returnVal = 1; } } // Returing the result of this method, so that the relevant media items can be sorted accordingly return returnVal; }); // Once the sorting has completed, calling the callback passed in earlier, to notify the route that this // process has completed (no need to pass back any data, as it was the array within the database which was // sorted) cb(); }; // Creating the media item schema, from which all media item documents will be based upon. Documents based on the // model of this schema will contain all of the properties listed below. Again, referencing the owner of this media // item by their ObjectId, so that if I ever need to get information on them, I can use .populate() on the query to // the media items collection, to return the owner document aswell (much like an SQL table JOIN) var MediaItemSchema = new Schema({ owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, file: { size: Number, path: String, filename: String, destination: String, mimetype: String, encoding: String, originalname: String, fieldname: String }, uploadedAt: { type: Date, default: Date.now }, mediaType: { type: String, required: true }, fileTitle: { type: String, required: false }, filePath: { type: String, required: true }, indexPosition: { type: Number, default: 0 }, category: { type: String, default: "none" } }); // Adding middleware to the media item schema, so that all instances of the models created from this schema // will inherit these. Immediatley after a media item is saved to the database, this middleware will be envoked, // so as to ensure it's ID is also added to the portfolio of the owner which uploaded it. This middleware takes in // no req, res or next parameters, as it occurs after the event has occurred. MediaItemSchema.post('save', function (mediaItem) { // Finding the portfolio document which belongs to the user that uploaded this media item, by accessing // it's owner property. PortfolioModel.findOne({ owner: this.owner }, {}, function (err, portfolio) { if (err) { console.log("MODELS - Could not find the portfolio of this user"); } else { // Adding the id of this media item to the media items array of this users portfolio portfolio.pages.home.mediaItems.push(mediaItem._id); // Resaving this portfolio to the database, with it's updated media items array portfolio.save(function (err) { if (err) { console.log("MODEL - could not add this media item to the users portfolio"); } else { console.log("MODEL - successfully saved media item to the users portfolio") } }); } }); }); // Adding middleware to the media item schema, so that all instances of the models created from this schema // will inherit these. This method occurs just before a media items is removed from the database. The purpose // of this is that I want to remove the id of this media item from the array of media items in the portfolio, so // that the next time the page is loaded, the server does not look for this media item MediaItemSchema.pre('remove', function (next) { // Finding the portfolio document which belongs to the user that uploaded this media item, by accessing // it's owner property. PortfolioModel.findOne({ owner: this.owner }, {}, function (err, portfolio) { // Looping through all of the media items of this owner's portfolio, to find the one that was just deleted for (var i = 0; i < portfolio.pages.home.mediaItems.length; i++) { // Checking if the current media item id is equal to the id of the media item that is about to be // removed from the database if (portfolio.pages.home.mediaItems[i].equals(this._id)) { // Found the id of the media item that is being deleted. Removing it from the mediaItems array // of the portfolio by splicing it at it's index and overwritting one portfolio.pages.home.mediaItems.splice(i, 1); // Resaving this portfolio to the database, with it's updated media items array portfolio.save(function (err) { if (err) { console.log("MODELS - could not remove media item from portfolio - " + err); } else { console.log("MODELS - Media item removed from portfolio"); } }); } } // Calling the next() method of the middleware, as passed in above, so that the router // can continue dealing with the request in other routes next(); }); }); // Generating models for each of the schemas created above var UserModel = mongoose.model("User", UserSchema); var PortfolioModel = mongoose.model("Portfolio", PortfolioSchema); var MediaItemModel = mongoose.model("MediaItem", MediaItemSchema); // Creating an object, which contains all of the database models (templates for // documents in the database) so that it can be used as the module export, and // so any route that requires this module can then access these modules directly // from the object that is returned to them. These models can then be used to generate // new documents instances, or to query the relevant collections to add, update, remove // and view the data within them. var databaseModels = { User: UserModel, MediaItem: MediaItemModel, Portfolio: PortfolioModel } // Setting the module exports to be equal to the object created above, // which contains all of the database models (document templates for the // database), so that they can be shared throughout multiple routes module.exports = databaseModels;<file_sep>/public/javascripts/adminScript.js jQuery(document).ready(function ($) { console.log("Admin Script Loaded"); // Storing the current value of the portfolio URL, so that if the user edits it later on, and // wants to undo this action, it's original value can be restored var originalPortfolioURL = $("#currentPortfolioURL").text(); // Creating a variable to store the number of which heading of the accordion should be opened // when the page loads (based on the cookie stored for this element). Would prefer to be doing // this the same way as with the .tabs() elements (i.e. in the main script file, looping through // them and setting their options accordingly) but if I do that with a .accordion() the result is // the accordion opening at it's default, and then quickly changing to the correct heading (which // doesn't look very well) var openOptionsOnTab = 0; // Getting the cookie data of this element's cookie, by passing it's id to the getCookieData() method // I created in the main script file. This will return an object with two properties - exists and value var cookieData = getCookieData("#adminOptionsAccordion"); // If this cookie already exists, then this is the number of the accordion heading the user was on when the // page last loaded, and hence should be the heading they are on when it reloads if (cookieData.exists) { openOptionsOnTab = parseInt(cookieData.value); } else { // Since this cookie does not already exist, creating a new one, with the name of the element and the // default accordion heading value of 0 (i.e. the first heading in the accordion) document.cookie = "adminOptionsAccordion=0"; } // Calling the jQuery UI accordion() method on the admin options panel, so that it will function as an // accordion menu. Passing in options, in the form of an object, which use the value sourced from the relevant // cookie above to activate the correct tab first (i.e. the one the user was last on), and setting the heightStyle // to be equal to content, so that each panel in the accordion can resize accordingly to fit it's own content $("#adminOptionsAccordion").accordion({ active: openOptionsOnTab, heightStyle: "content" }); // Using the jQuery UI sortable() function, to make the contents of the div which contains the // users media items sortable i.e. they can be reordered by dragging and dropping. Setting the // containment to 'parent' so that these elements cannot be dragged outside the box. Setting the // cursor to 'move' so that it's symbol changes while the user is dragging. Setting the 'cancel' // function to be invoked if the user tries to drag an element while over it's caption, select // category dropdown or the options within it, as this should not be detected as a dragging event // but as a click. $("#sortable").sortable({ grid: [1, 1], cursor: "move", cancel: "figcaption, select, option", stop: function (event, ui) { resizeFigures(); // Creating a temporary array to store the id's and index positions of each of the media // items (figures) on the page, so that they can be passed to the server as one stringified // JSON object var mediaItemOrder = []; // Looping through each of the figures (media items) on the page $.each($("figure"), function (index) { //console.log($(this).find("figcaption").text() + " is at index " + index); // Pushing the media id and index position of this figure into the temporary array // created above, so that it can be sent, along with the rest of the media item's // positions, to the server to be stored, so that the new order of these media items // will be saved in the database (so that in the admin panel, and on the portfolio // page, the media items will display in the order specified by the admin) mediaItemOrder.push({ mediaId: $(this).attr("id"), indexPosition: index }); }); // Sending an AJAX POST request to the server, passing in the new order of the media items // (as stored in the temporary variable above). Stringifying these, so the array can be parsed // as JSON on the server side. This POST request will receive a response from the server, but as // this is only to end the request/response cycle, and will contain no additional data, not adding // a callback to the request. $.post("/admin/changeMediaOrder", { newOrder: JSON.stringify(mediaItemOrder) }); } }); // Generating a select option element above each of the media item figures on the page, so that the user can // assign different categories to each of them directly $("#sortable figure").each(function (index) { // Generating a new class name for this select option, using the index provided var mediaCategoryClass = "mediaCategory" + index; // Finding the div within this figure, which is a placeholder for where this select element should be added. // Assigning the mediaCategory class, along with it's own individual class (defined above) $(this).find(".categoryOptions").append("<select class='mediaCategory " + mediaCategoryClass + "'></select>"); // Finding the new select element that was just created, and appending the default "none" option to it $("." + mediaCategoryClass).append("<option value='none' selected>-Category-</option>"); // Looping through each category defined in the app (as listed in the categories section of the admin panel) $(".category").each(function (index) { // Appending a new option for each of the categories, to the new select option just created above. Setting // the value and the content to be equal to the name of the category $("." + mediaCategoryClass).append("<option value='" + $(this).text() + "'>" + $(this).text() + "</option>"); // Checking if the name of this category matches with the select options parent element's data-category attribute // i.e. if this is the category of the current figure (which would have been added to the parent's data attribute // while rendering on the server) if ($(this).text() == $("." + mediaCategoryClass).parent().attr("data-category")) { // Since this is the category of this figure, setting the value of this new select element to be // equal to it (i.e. to reflect the media item's current category) $("." + mediaCategoryClass).val($(this).text()); } }); }); // Checking if a user has clicked on a select element i.e. the category pickers for each media item $("#sortable figure select").click(function (event) { // Checking if this select element has more than just the default option if ($(event.target).find("option").length <= 1) { // Since there are currently no options in this select element, then there must be no categories // in this portfolio, so triggering a click event on the categories section of the admin panel to // open the accordion menu accordingly, to encourage the user to add some categories $("#categorySettings").trigger("click"); // Setting the location href to be equal to the categories heading id, so that if the user is too // far down the page to see the panel open, they will be scrolled back up to it location.href = "#categorySettings"; } }).change(function (event) { // Every time a change occurs on a select element (i.e. a change of category) sending an AJAX POST request // to the server, with the id of the media item, and the new category to which it has been assigned. No data // is needed from the response, so not setting a callback for this request $.post("/admin/changeMediaCategory", { mediaItem: $(event.target).parent().parent().parent().attr("id"), category: $(event.target).val() }, function (serverResponse) { // Updating the data attribute of the select option container for this media item, to reflect the new category // for this media item $("figure[id='" + serverResponse.changedMediaId + "']").find(".mediaCategory").parent().attr("data-category", serverResponse.changedCategory); }); }); // Each time a figcaption looses focus, triggering an AJAX post request to the server (i.e. to change that // media item's title) $("figcaption").blur(function (event) { $.post("/admin/changeMediaTitle", { mediaId: $(event.target).parent().attr("id"), newTitle: $(event.target).text() }, function () { // Once the server responds, calling the resizeFigures method (as declared in the main script file) // so that all the figures will be the same size resizeFigures(); }); }); // Each time a keypress is detected on an element that accepts user input, checking if it was the enter key // that was pressed (so that this can then trigger these element's save/add options to be called). Also ensuring // that the enter key's default line break does not occur, as this would not be an acceptable input into these // fields $("figcaption, p, input").keypress(function (event) { // Checking if it was the enter key that was pressed if (event.which == 13) { // Checking if the current input field was "newCategory" if (event.target.id == "newCategory") { // Triggering a click on the addCategory button, so the new category can be added $("#addCategory").trigger("click"); } else if (event.target.id == "currentPortfolioURL") { // If the current input field was for changing the user's portfolio url, then triggering // a click on the save button of this field so that it can be saved to the server $("#savePortfolioURL").trigger("click"); } // Preventing the default behaviour of the enter key (i.e. not allowing it to add a line break to the // input) event.preventDefault(); // Removing focus from the element that triggered this event, so it's value will now be // saved (either through the triggering of a click above, or through it loosing focus - as // seen below) $(event.target).blur(); } }); // Each time the value in the contact info text area is changed, triggering the paragraph within the same area // to lose focus, so that it's new value can be sent to the server (as seen below) $("#contact textarea").change(function (event) { // Only targeting the first returned paragraph, as if this query were to return more than one paragraph, // multiple requests would be made to the server (i.e. one for each) $("#contact p").first().trigger("blur"); }); // When any paragraph in the contact details section of the admin panel looses focus (which could also include // the textarea, as seen above this triggers a blur event on a paragraph when it is changed - as it has not blur // event of it's own) $("#contact p").blur(function (event) { // Sending an AJAX request to the server with the current values of the user's name, email, info and phone. // The purpose of sending these all in one request, is that on the server side it is much faster to update // the document, than to find specific fields each time, so I just update these four for every request $.post("/admin/changeContactDetails", { name: $("#contactName").text(), email: $("#contactEmail").text(), info: $("#contactInfo").val(), phone: $("#contactPhone").text() }); }); // If a user clicks on their contact picture (while in the admin panel) triggering the admin settings accordion // to open on the contact picture panel, just incase they were clicking on it to try and change it. $("#contactPicture").click(function (event) { // Triggering a click on the contact picture settings heading of the admin accordion options so it will open $("#contactPictureSettings").trigger("click"); // Setting the location href to be equal to the id of this heading, so that if the user is too far down the // screen to see it opening, they will be taken back up to the contact pictures settings panel location.href = "#contactPictureSettings"; }); // Everytime a media item's deleteMedia icon is clicked, sending a request to the server to remove it $(".deleteMedia").click(function (event) { // Swapping the deleteMedia button's icon from a trash can to an hour glass, so that if there is a time // delay, the user will know that the request is in progress. Also unbinding the click event from this button // so that only one delete request will be sent to the server (i.e. they cannot click it again) $(event.target).removeClass("glyphicon-trash").addClass("glyphicon-hourglass").unbind("click"); // Sending an AJAX request to the server, with the id of the media item the user want to delete. $.post("/admin/deleteMedia", { mediaId: event.target.id }, function (responseData) { // As this was an AJAX request, there may be some time delay in the button being clicked, and the media // item being deleted from the server. Once the server response to say that this media item has been // deleted (i.e. through the id on the response data object) I use the to find the deleteMedia button // that was originally clicked (by it's id - which was the media item's id), and then remove the div which // contains the figure, of the media item that was just removed. Removing this div from the DOM, so the // deletion of this media item is reflected client side aswell, without having to reload the page $(".row > div").find("span[id='" + responseData.mediaId + "']").parent().parent().parent().parent().remove(); }, "json"); }); // When a user clicks on the button to edit their portfolio URL. The reason I am using a button system for this // field, as opposed to the click and type method I use for everything else, is that I feel this is the most // significant input on the screen, as if someone were to inadvertantly change their portfolio URL, and employeer // may no longer be able to find it. This method allows them to cancel the edit, before it is sent to the server $("#editPortfolioURL").click(function (event) { // Setting the content editable property of the paragraph holding the URL to true (i.e. so it can be manipulated). // Calling focus on it, so the user knows it is now editable $("#currentPortfolioURL").prop("contenteditable", "true").focus(); // Setting the status icons to default to OK, i.e. as the user already owns the url in this box, it is // technically available (to them only) $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ok-circle"); // Hiding the "edit" button $(this).hide(); // Displaying the cancel and save button $("#cancelPortfolioURL").show(); $("#savePortfolioURL").show(); }); // When a user clicks the cancel button while editing their portfolio URL, it is reset to it's original value, // and no request is made to the server $("#cancelPortfolioURL").click(function (event) { // Removing the content editable attribute from the paragraph, and removing the focus from it, so the // user can no longer type into it. Resetting the text value of this element to be equal to it's original // value $("#currentPortfolioURL").removeAttr("contenteditable").blur().text(originalPortfolioURL); // Removing all classes from the portfolio status icon, as this no longer needs to display whether or // not the url is available or not $("#portfolioURLStatusIcon").removeAttr("class"); // Hiding the cancel button (which was just clicked on), as well as hiding the save button $(event.target).hide(); $("#savePortfolioURL").hide(); // Displaying the edit button again $("#editPortfolioURL").show(); }); // If a user chooses to save their edited portfolio url, first checking if it is available and then // sending it to the server to update their portfolio accordingly $("#savePortfolioURL").click(function (event) { // Checking that the new url is not equal to the existing one (i.e. no change was made) if ($("#currentPortfolioURL").text() != originalPortfolioURL) { // Adding an hour glass beside the portfolio link, so the user knows it is being updated $("#portfolioLinkStatus").addClass("glyphicon-hourglass"); // Disabling the edit button, so the user cannot try to make an edit while the url is being // updated $("#editPortfolioURL").attr("disabled", "disabled"); // Temporarily storing the requested URL, cast to lowercase and with all spaces removed from it var requestedURL = $("#currentPortfolioURL").text().toLowerCase().replace(/ /g, ""); // Making an AJAX request to the server to see if this url is available (or if someone else has // already claimed it) using the checkCredentialsAvailable() method I declared in the main script // class. Passing in null for the username (as no username needs to be checked right now), the // lowercase version of the url (with no spaces) and a callback to which the response data wil be passed // once the server responds checkCredentialsAvailable(null, requestedURL, function (responseData) { // Checking the response data to see if this url is currently available if (responseData.portfolioURLAvailable) { // Sending an AJAX request to the server, with the requested url (as sourced from the // response data, to ensure that it hasn't changed since we last checked if it was available) $.post("/admin/changePortfolioURL", { newPortfolioURL: responseData.portfolioURL }); // Setting the global originalPortfolioURL to be equal the the requested url, so that the // next time the user makes a change to it, we can test it against its new current value originalPortfolioURL = responseData.portfolioURL; // Updating the link to the user's portfolio (at the top of the admin screen) to link to the // new portfolio url (preceeded by the website's url, which is also passed back in the response // i.e. so that the link will look correct regardless of whether the app is running locally or remotely) $("#portfolioLink") .attr("href", responseData.url + responseData.portfolioURL) .text(responseData.url + responseData.portfolioURL); // Enabling the edit button, so the user can edit the url again $("#editPortfolioURL").removeAttr("disabled"); } else { // As these credentials are not available, resetting the url input to be equal to it's previous value $("#currentPortfolioURL").text(originalPortfolioURL); } // Removing the hour glass beside the portfolio link $("#portfolioLinkStatus").removeClass("glyphicon-hourglass"); // Removing all classes from the status icon, as it no longer needs to display feedback on whether this url // is available or not $("#portfolioURLStatusIcon").removeAttr("class"); }); } // Displaying the edit button $("#editPortfolioURL").show(); // Hiding the cancel and save buttons $("#cancelPortfolioURL").hide(); $("#savePortfolioURL").hide(); // Removing the content editable attribute from the url input, as the user has finished editing it $("#currentPortfolioURL").removeAttr("contenteditable"); }); // Each time the user releases a key while typing in the url input field, sending an AJAX request to the server // to check if it is available (i.e. so that the status icon can give them feedback on this before they decide to // change their url) $("#currentPortfolioURL").keyup(function (event) { // Temporarily storing the requested URL, cast to lowercase and with all spaces removed from it var requestedURL = $("#currentPortfolioURL").text().toLowerCase().replace(/ /g, ""); // Checking if the new value of the url input is equal to it's previous value (i.e. no change occurred) if ($(this).text() == originalPortfolioURL) { // Setting the status icons to default to OK, i.e. as the user already owns the url in this box, it is // technically available (to them only) $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ok-circle"); } else { // Making an AJAX request to the server to see if this url is available (or if someone else has // already claimed it) using the checkCredentialsAvailable() method I declared in the main script // class. Passing in null for the username (as no username needs to be checked right now), the // lowercase version of the url (with no spaces) and a callback to which the response data wil be passed // once the server responds checkCredentialsAvailable(null, requestedURL, function (responseData) { // Logging out the response data from the server, to see if the url is available or not console.log(responseData.portfolioURLAvailable); // Checking if the url is available or not if (responseData.portfolioURLAvailable) { // Changing the status icon to a green circle, as this url is available $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ok-circle"); } else { // Changing the status icon to a red circle, as this url is not available $("#portfolioURLStatusIcon").attr("class", "glyphicon glyphicon-ban-circle"); } }); } }); // Each time a user adds a new category, a request is sent to the server to update the list of category's on this // portfolio. These category's are used on the admin panel to decide which options to display in the select elements // on each media item, and on the portfolio page to decide which options to give visitors to filter the users // portfolio by $("#addCategory").click(function (event) { // Checking that the new category has a value before allowing it to be sent to the server if ($("#newCategory").val().length > 0) { // Sending an AJAX request to the server with the name of the new category $.post("/admin/addNewCategory", { newCategory: $("#newCategory").val() }, function (serverResponse) { // Since this is an asynchronous request, there will be a time delay between the user clicking the button, and // the category being added to the server, so waiting until the server resonds to add the new category to // the list of existing category's (directly above the add button) $("#categories").append("<div class='row'><div class='col-xs-offset-2 col-xs-8'>" + serverResponse.newCategory + "</div><div class='col-xs-2'><span class='deleteCategory glyphicon glyphicon-trash' aria-hidden='true' data-deletecategory='" + serverResponse.newCategory + "'></span></div>"); // Returning the focus to the new category input, so that the user can continue to type and add new category's // without having to click into it again $("#newCategory").val("").focus(); // Enabling the add button $("#addCategory").removeAttr("disabled"); // Looping through each of the select elements on the media items, and adding this new category as an option $(".mediaCategory").each(function (index) { // Adding a new option to this select element, using the name returned in the response data, just incase // multiple category's are added one after the other, and come back in the wrong order, I want to // ensure I am adding the right one $(this).append("<option value='" + serverResponse.newCategory + "'>" + serverResponse.newCategory + "</option>"); // Checking if the name of this category matches with the select options parent element's data-category attribute // i.e. if this is the category of the current figure (which would have been added to the parent's data attribute // while rendering on the server) console.log($(this).parent().attr("data-category") + "- -" + serverResponse.newCategory); if ($(this).parent().attr("data-category") == serverResponse.newCategory) { // Since this is the category of this figure, setting the value of this select element to be // equal to it (i.e. to reflect the media item's current category) $(this).val(serverResponse.newCategory); } }); }, "json"); // Temporarily disabling this button, so that users can't accidentally send multiple requests to the server // while waiting for the first to go through $("#addCategory").attr("disabled", "disabled"); } }); // Dynamically generated category's were not being detected by click(), so using on() instead (as these // new elements can then have the click event bound to them). Detecting clicks on their deleteCategory buttons, // so that a request can be sent to the server to delete them $("#categories").on("click", ".deleteCategory", function (event) { // Sending an AJAX request to the server, with the id of the delete button that was clicked (which will be // equal to the name of that category) $.post("/admin/deleteCategory", { deleteCategory: $(event.target).attr("data-deletecategory") }, function (serverResponse) { console.log("del response from db - " + serverResponse.deletedCategory); // Looping through the select elements of media item, so that this category can be removed from their // options, once the server responds $(".mediaCategory option").each(function (index) { // Checking if this category was the current category of this media item if ($(this).text() == serverResponse.deletedCategory) { // Removing the selected attribute from the option, so that it no longer appears as the // selected option on this media item $(this).removeAttr("selected").remove(); // Setting the value of this media item's select element to be "none" i.e. the default // value for select elements $(this).parent().val('none'); // Decided not to reset the category of this media item on the server, as if the user wants // to re-add this category later on, the media items that were previously assoicated with it // will automatically reset to it. Even though media items may maintain a category that doesn't // exist, unless it is listed as a category of the portfolio it will not be listed as such, in // the admin panel nor the portfolio page (unless the category is added again) } }); // Finding the category element in the list of category's in the admin panel, and removing it (based // on the category that the server has just deleted, incase responses come back in the wrong order) $("#categories").find("[data-deletecategory='" + serverResponse.deletedCategory + "']").parent().parent().remove(); }, "json"); // Swapping the deleteCategory button's icon from a trash can to an hour glass, so that if there is a time // delay, the user will know that the request is in progress. Also unbinding the click event from this button // so that only one delete request will be sent to the server (i.e. they cannot click it again) $(event.target).removeClass("glyphicon-trash").addClass("glyphicon-hourglass").unbind("click"); }); // Checking the forms that contain file uploads, to ensure a file has been selected before // the form can be sent to the server $("#uploadMedia, #changeContactPicture").submit(function (event) { // Creating a boolean which will be used to determine if this form should be allowed to // submit or not. This will only be set to true if the form that triggered the event has // at least one file in it var allowSubmit = false // Finding the file input of the form that triggered this event, and checking if the length // of it's value is greater than 0 (i.e. does it have a file included) if ($(event.target).find("input[type='file']").val().length > 0) { // Changing allow submit to true, so that this form can be sent to the server allowSubmit = true; // Checking which form triggered the event if ($(event.target).attr("id") == "changeContactPicture") { // Since the user just uploaded a new contact picture, setting the cookie for the tab pages // in the admin panel to be 1 (i.e. so when the page reloads, the user can see the result in the // contact page) document.cookie = "adminPagesTabs=1"; } else if ($(event.target).attr("id") == "uploadMedia") { // Since the user just uploaded a media item, setting the cookie for the tab pages // in the admin panel to be 0 (i.e. so when the page reloads, the user can see the results in the // home page) document.cookie = "adminPagesTabs=0"; } } else { // Since the file input in this form contains no file, adding the form warning class to it so that // the user understands why the form would not submit $(event.target).find("input[type='file']").addClass("formWarning"); } if (allowSubmit) { // Disabeling the submit button of the form so that the user cannot accidentally submit // it twice while it is still being processed (this will reset once the file has been uploaded // as the page will be refreshed) $(event.target).find("input[type=submit]").attr("disabled", "disabled"); } // Returning the value of allowSubmit to the function, which will determine whether or not this form // can be submitted to the server return allowSubmit; }); // If a user has no media items uploaded yet, a button will appear in the home panel to encourage them // to upload some media. When this button is clicked, triggering a click on the "upload media" section // of the accordion menu, so that if it is not already open, it will be activated $("#triggerUploadMedia").click(function (event) { $("#uploadMediaSettings").trigger("click"); }); });<file_sep>/custom_modules/database.js // Requiring the mongoose module, which I will use to make the connection to the // database (either locally - when in development mode, or remotely using MongoLab // for the Azure server) var mongoose = require('mongoose'); // Creating a variable to be either store the connection string to the MongoLab database // (which will only be available when the app is running on Azure, as this environment // variable has not been set locally) or the local database (which will be used for // local testing) var connectionString = process.env.CUSTOMCONNSTR_PortfolioBuilderMongo || "mongodb://localhost:27017/PortfolioBuilder"; // Creating a connection to the database, using the connection string specified above mongoose.connect(connectionString); // Logging out to the console that the connection to the database is being made, // so that I can monitor the console to ensure that this only happens once (even // when I require this module in multiple routes) console.log("Creating Database Connection - " + mongoose.connection.readyState); // Creating a variable to store the connection to the database, so I can set up // listeners on it, and then use it as the module exports object, so the connection // can be shared between multiple routes. var db = mongoose.connection; // Creating a listener for error events on the database connection db.on('error', function(err){ console.log("There was an error connection to the database - " + err); }); // Creating a listener for when the database connection is opened i.e // when the db.readyState equals "1" db.once('open', function() { console.log("Database Successfully connected"); }); // Setting the exports of this module to equal to the connection to the database // which I have just set up. This connection may not be fully set up when the export occurs, // but since the exports references this object, the readyState of the connection will be // updated accordingly module.exports = db;<file_sep>/public/javascripts/script.js jQuery(document).ready(function ($) { console.log("Main JS script loaded"); // Calling the jQuery UI tabs() method, to create tabbed portions of the pages i.e. // on the login screen, and in the admin panel $(".tabs").tabs(); // Every time the page loads, getting the previous tab index for any jQuery UI tabs() elments on // the screen, so that if the page has just reloaded, or the user was directed back here, they // see the same layout $(".tabs").each(function (index) { // Getting the cookie data of this element's cookie, by passing it's id to the getCookieData() method // I created below. This will return an object with two properties - exists and value var cookieData = getCookieData($(this).attr("id")); // If the cookie for this tab element already exists, getting it's value and setting the tabs element to this if (cookieData.exists) { $(this).tabs("option", "active", cookieData.value); } else { // Since the cookie does not already exist, creating a new one, with the same name as this tabs element // id, and the index value of the current tab it is on document.cookie = $(this).attr("id") + "=" + $(this).tabs("option", "active"); } }); // Everytime the window is resized, calling the same resizeFigures() method so that the figures // will be recalculated and the containers sized appropriatley $(window).resize(function () { // Calling the resizeFigures() method, as defined below. The purpose of this method is to // combat the issues with resizing of embedded objects (such as swfs and videos). As I wanted // to make each of these elements responsive (along with any other media elements on the page). // Each video and swf is wrapped in a container, and set to scale to the container's size. In order // to ensure that this container matches with the other figures on the screen, using this function // to find the largest figure, and then resizing all other figures and containers to match this. resizeFigures(); }); // Waiting until all elements on the page have loaded before resizing them window.onload = function () { console.log("Window Loaded"); // Calling the resizeFigures() method, as defined below. The purpose of this method is to // combat the issues with resizing of embedded objects (such as swfs and videos). As I wanted // to make each of these elements responsive (along with any other media elements on the page). // Each video and swf is wrapped in a container, and set to scale to the container's size. In order // to ensure that this container matches with the other figures on the screen, using this function // to find the largest figure, and then resizing all other figures and containers to match this. resizeFigures(); } // Every time an accordion is activated (i.e. clicked on) storing the current accordion index position in a // cookie so that if the page reloads, or the user is directed back here, they will see the same layout as before $(".accordion").on("accordionactivate", function (event, ui) { // Removing any warnings from form inputs, as when a user changes tabs they must no longer be trying to // submit a form $("form input").not("[type='submit']").removeClass("formWarning"); // Setting the cookie with the same name as this accordion element's id to be equal to the number of the // accordion heading it is now on document.cookie = $(event.target).attr("id") + "=" + $(event.target).accordion("option", "active"); + ";path=/"; }); // Every time a tab is activated (i.e. clicked on) storing the current tabs index position in a cookie so that // if the page reloads, or the user is directed back here, they will see the same layout as before $(".tabs").on("tabsactivate", function (event, ui) { // Resizing all figures again, as a change of tabs can cause the swfs to disappear resizeFigures(); // Removing any warnings from form inputs, as when a user changes accordion headings they must no longer // be trying to submit a form $("form input").not("[type='submit']").removeClass("formWarning"); console.log("Changing " + $(event.target).attr("id") + " to " + $(event.target).tabs("option", "active")); // Setting the cookie with the same name as this tab element's id to be equal to the number of the tab // it is now on document.cookie = $(event.target).attr("id") + "=" + $(event.target).tabs("option", "active"); + ";path=/"; }); }); // This function is called each time the page is reloaded, or the window is resized, to ensure that varying // types of content are all sized the same i.e. images, video and swfs function resizeFigures() { // Resetting each figure's minHeight to it's initial value, so that when the resizeFigures() funciton // runs, it is not basing it's new height value on the current dimensions of the figures $("figure").css("minHeight", "initial"); $("figure video, figure object, .objectContainer").css("height", $("figure img").height()); // Creating a temporary variable to store the largest height of the figures currently var maxFigHeight = 0; var maxImgHeight = 0; // Looping through each figure on the page, to find the current largest height $('figure').each(function () { // Using a ternary operator to test this figure's height against the current maximum figure height // detected. If this figure is taller, then updating maxFigHeight to reflect this, otherwise setting // maxFigHeight to equal it's current value maxFigHeight = maxFigHeight > $(this).height() ? maxFigHeight : $(this).height(); maxImgHeight = maxImgHeight > $(this).find("img").outerHeight() ? maxImgHeight : $(this).find("img").outerHeight(); }); $("figure").css("minHeight", maxFigHeight * 1.02); $(".objectContainer, video, object").css("height", maxImgHeight); console.log("Figures resized"); } // Creating an asynchronous function to check if the credentials a user has supplied are available. // Takes in three parametres. The requested username, requested url, and the callback function to which // the response data should be returned when a response is received from the server function checkCredentialsAvailable(username, url, cb) { console.log("Checking if the username - " + username + " and url - " + url + " are available"); $.post("/checkCredentialsAvailable", { requestedUsername: username, requestedPortfolioURL: url }, function (serverResponse) { console.log("Username available = " + serverResponse.usernameAvailable + " and url available = " + serverResponse.portfolioURLAvailable); // Passing the response data back to the callback function cb(serverResponse); }, "json"); } function getCookieData(findCookie) { // Creating an array that stores all of the cookies of the session as seperate // elements. Using .replace() to remove all spaces from this string of data, and // the .split() method to set the points at which the string of cookies needs // to be seperated i.e. after each ; var allCookies = document.cookie.replace(/ /g, "").split(";"); var cookieData = { exists: false, value: "" } for (var i = 0; i < allCookies.length; i++) { if (allCookies[i].split("=")[0] == findCookie) { cookieData.exists = true; cookieData.value = allCookies[i].split("=")[1]; console.log(findCookie + " exists = " + cookieData); } } return cookieData; }<file_sep>/custom_modules/cryptoEncryption.js // Requiring the built in Crypto module of NodeJS var crypto = require('crypto'); // Setting the algorithm of the encryption to be AED 256bit Counter var cryptoAlgorithm = ("aes-256-ctr"); // Setting the password key (which will be used to hash the encryption) to be // equal to the value stored in the environment variable (available locally and on // the azure site) var cryptoPasswordKey = process.env.CRYPTO_PASSWORD_KEY; // Creating a cryptoEncryption object, which will be the exports object of this module. // This object contains two methods, one to encrypt data, and the other to decrypt data. var cryptoEncryption = { encrypt: function(text) { // Function sourced from an example use of Crypto // https://github.com/chris-rock/node-crypto-examples/blob/master/crypto-ctr.js var cipher = crypto.createCipher(cryptoAlgorithm, cryptoPasswordKey) var crypted = cipher.update(text, 'utf8', 'hex') crypted += cipher.final('hex'); return crypted; }, decrypt: function(text) { // Function sourced from an example use of Crypto // https://github.com/chris-rock/node-crypto-examples/blob/master/crypto-ctr.js var decipher = crypto.createDecipher(cryptoAlgorithm, cryptoPasswordKey) var dec = decipher.update(text, 'hex', 'utf8') dec += decipher.final('utf8'); return dec; } }; // Returning the cryptoEncryption object as the export when this module is required module.exports = cryptoEncryption; <file_sep>/routes/portfolio.js var express = require('express'); var router = express.Router(); // Requiring the databaseModels custom module, which returns and object containing all the // models for documents inthe database i.e. User, MediaItem and Portfolio. Storing the User // MediaItem, and Portfolio models in their own variables so they can be accessed in this module i.e. // to query, add, remove and update documents in their relevant collections of the database var databaseModels = require("../custom_modules/databaseModels"); var User = databaseModels.User; var Portfolio = databaseModels.Portfolio; var MediaItem = databaseModels.MediaItem; // All requests to view a user's portfolio. Visitors to the site do not need to be logged in to access // this section of the app router.get("/:portfolioURL", function (req, res, next) { // Using the params property of the request object to determine which portfolio URL the user is looking for. // Then querying the Portfolio module to find a portfolio with a matching URL. Using the // .populate() method to return the media items and owner, whose ObjectId's are referenced within the relevant // properties of the portfolio document (similar to a SQL table JOIN) Portfolio.findOne({ portfolioURL: req.params.portfolioURL }).populate("pages.home.mediaItems owner").exec(function (err, portfolio) { if (err) { console.log("Index - Could not check if this portfolio exists - " + err); } else { if (portfolio == null) { // This portfolio does not exist (it may never have existed, or the user may have changed // the URL) console.log("Index - This portfolio does not exist"); // Rendering the noportfolio view to let the user know this portfolio does not exist res.render("noportfolio", { title: "/ " + req.params.portfolioURL + " does not exist" }); } else { console.log("INDEX - portfolio exists"); // Calling the sortMediaItems() function I created on the modules object of the Portfolio schema // in the databaseModels module. This method sorts the media items of the database according to // index position and date. Once the sort is complete, the portfolio page can then be rendered. // Passing the relevant data needed to set up the page. Thanks to the populate() method, I can access // all Portfolio, Owner and MediaItems data relating to this protfolio from the one result object - portfolio portfolio.sortMediaItems(function () { console.log("PORTFOLIO - media items sorted"); res.render("portfolio", { title: "Welcome to " + portfolio.owner.firstName + "'s Portfolio", mediaItems: portfolio.pages.home.mediaItems, contactPage: portfolio.pages.contact, categories: portfolio.pages.home.categories }); }); } } }); }); module.exports = router;<file_sep>/app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Requiring Multer (to parse multi-part form data) var multer = require('multer'); // Requiring Mongoose (to set up the connection to the Mongo database) var mongoose = require('mongoose'); // Requiring Express-Session (to handle sessions) var session = require('express-session'); // Requiring MongoStore (to create storage in the database for sessions) var MongoStore = require('connect-mongo')(session); // Requiring checkDirectories, so that I can pass the array of directories I need // for this app to it, and if they don't exist they will be created var checkDirectories = require('./custom_modules/checkDirectories'); // Requiring databaseConnection, which is the module in which I have set up // the mongoose connection to the database. The exports of this module // returns the connection, and so it can now be shared between routes. In this // file, it will be used to share the connection with the MongoStore (to store // sessions in the database) var databaseConnection = require("./custom_modules/database"); // Requiring the databaseModels custom module, which returns and object containing all the // models for documents in the database i.e. User, MediaItem and Portfolio. var databaseModels = require("./custom_modules/databaseModels"); var User = databaseModels.User; // Specifying the root path of the uploads directories, so that it // can be prepened to each of the subdirectories below. Checking if // the application is in the development environment (by checking // if the NODE_ENV connection string is accessible) or in the Azure // environment (as the site will be running in a the /bin folder // and so the public directory will be one level up from the site) var mainUploadDirectory = process.env.NODE_ENV == "development" ? './public/media_uploads/' : "../public/media_uploads/"; // Creating an array to store all of the directories required for storing // file uploads, including the main directory (as declared above). Prepending // each of the subdirectories with the main directory path, so that they will // appear as a folder hierarchy. var uploadsDirectories = [ mainUploadDirectory, mainUploadDirectory + "image", mainUploadDirectory + "swf", mainUploadDirectory + "video", mainUploadDirectory + "contactPicture" ]; // Using the custom module I created to check that all of the folders required // within the uploads directory exist. If they don't, then they will be created. // Only calling this function when the server starts up, as there should be no // reason that this directories would end up being deleted after this point. // If I were to check/create these directories each time a file were uploaded, // it would significantly increase the time required to store the files. Passing // the array which contains each of the directories for this file structure console.log("Checking if the upload directories exist"); checkDirectories(uploadsDirectories); // Setting up variables to store the four main routes of my app, so that they can be passed to the // middleware functions below var routes = require('./routes/index'); var admin = require('./routes/admin'); var authentication = require('./routes/authentication'); var portfolio = require('./routes/portfolio'); var app = express(); // Creating a fileter for Multer, so that only certain file types, uploaded by logged in users, // will be accepted for upload to the server. All other files will be rejected and will never reach // the routes of the app var multerFileFilter = function (req, file, cb) { // Checking if a user is currently logged in (based on having a _userId on their request object) if (req.session._userId == null) { console.log("MULTER FILTER - No user is currently logged in. Rejecting this file upload"); // No error, but rejecting this file as their is no user currently logged in cb(null, false); } else { console.log("MULTER FILTER - This user is currently logged in. Accepting this file upload"); // Getting the media type of this file by splitting the mimetype (e.g. image) at // the "/" and then taking the first half of this new array of strings i.e. image. // Storing the second half of this string, i.e. file type (e.g. jpg) file.mediaType = file.mimetype.split("/")[0]; file.fileType = file.mimetype.split("/")[1]; // If the file type is "x-shockwave-flash" then just storing it as a "swf" if (file.fileType == "x-shockwave-flash") { // Setting both the mediaType and fileType to be equal to "swf"(the original mimetype will // still exist in the file object) file.mediaType = file.fileType = "swf"; } // Logging out the file type to the console (testing purposes) console.log("MULTER FILTER - This file is a " + file.mediaType + " file. More specifically, a " + file.fileType + " file."); if (file.mediaType == "image" || file.mediaType == "video" || file.fileType == "swf") { console.log("MULTER FILTER - This is a supported filetype for this application - accepting this file"); // Accepting these files. There is a user logged in, and these are files the portfolios can display cb(null, true); } else { console.log("MULTER FILTER This is not a supported filetype for this application - rejecting this file"); // Rejecting these files. These are not files that the portfolio is able to display cb(null, false); } } } // Creating diskStorage options for the multer middleware, to determine the destination and filename // of each file before it is stored on the server var multerStorage = multer.diskStorage({ destination: function (req, file, cb) { // Creating a pathName variable, to store the path to the directory that this file // should be stored in (this will be decided based on the filetype). This variable // will then be passed to the destination function's callback, to pass the required // pathName back so that multer knows where to store the file var pathName; // Deciding which folder to store the file in, depending on it's file type if (file.fieldname == "contactPictureFile") { pathName = mainUploadDirectory + "/contactPicture" } else if (file.fileType == "swf") { // Setting the pathname so that multer knows where to store swf files pathName = mainUploadDirectory + '/swf'; } else { // Setting the pathname so that multer knows where to store all other video and image files pathName = mainUploadDirectory + "/" + file.mediaType; } console.log("MULTER STORAGE - " + pathName); // Increasing the time out for the request, as file uploads take a long time on Azure - not really // improving the issue for videos through req.setTimeout(60000, function (err) { console.log("MULTER - Server timed out " + err); }); // Using the destination function's callback to pass the required pathname back // so that multer knows where to store this file cb(null, pathName); }, filename: function (req, file, cb) { // Setting the filename of this file to be equal to the current data stamp plus it's original filename // i.e. so it will have a unique name on the server. Returning this name to the callback cb(null, Date.now() + "_" + file.originalname); } }); // Setting up Multer, passing in the file fileter and disk storage options, which will both be called on every // file that gets uploaded to the server (even if they are uploaded in the one request, they will each be // dealt with seperatley) var multerUpload = multer({ fileFilter: multerFileFilter, storage: multerStorage }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // Creating a new instance of the Mongo, setting it's mongoose connection to share the // same connection to the database as the rest of the app (as exported from the database module) // module) var mongoStore = new MongoStore({ mongooseConnection: databaseConnection }); // Setting the app to use sessions for all requests to the server. Setting resave to false (so if there is no change to // a session object, it won't have to be resaved). Not saving uninitialised sessions i.e. ones that have had no // new properties added to them. Setting the store to equal the new MongoStore created above. Finally, if a session // is unset (destroyed) then removing it from the database aswell app.use(session({ secret: 'sessionSecret', resave: false, saveUninitialized: false, store: mongoStore, unset: "destroy" })); app.use("/", multerUpload.any()); // Specifying the routes for each of the paths specified. // This middleware deals with general request such as the home page, logging in /out etc app.use('/', routes); // This middleware deals with users wanting to see other users portfolios (no login required) app.use("/portfolio", portfolio); // Passing all requests for admin, to ensure that user which is not logged in // can not get into the admin secion. app.use("/admin", authentication); // If a request has made it through the above, then the user must be logged in, and can // be granted access to the admin section app.use('/admin', admin); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
54372eb2e1a2cab1b63aa97ebe3b46bd65ab5cb8
[ "JavaScript", "Markdown" ]
10
JavaScript
pigottlaura/SSP-Assignment-02-PortfolioBuilder
bd043a25f1de79636f3205cee9e998f385a4b453
48b8fbc279e8a74c5a99de7fb40c32c7828182f9